I am working on an android app and using Spinner at many places in my app. What I want is to change the background color of the selected item of spinner, so that one can easily identify which item is currently selected.
I have already checked this link Setting background color for Spinner Item on selection but doing so will change the selected textview background color but do not change its color in dropdown list and I want to change the background color of the selected textview when I will see the dropdown list.
I want to change the color of selected item in list not on spinner, please see the image below.
How can I do this? Please, can someone help me here?.
Thanks a lot in advanced.
Create background color. By default each activity in Android has a white background. To change the background color, first add a new color definition to the colors. xml file in the values resource folder like the following.
You need to implement below method in your adapter class:
It will help you:
int selectedItem = -1;
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list) {
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
View v = null;
v = super.getDropDownView(position, null, parent);
// If this is the selected item position
if (position == selectedItem) {
v.setBackgroundColor(Color.BLUE);
}
else {
// for other views
v.setBackgroundColor(Color.WHITE);
}
return v;
}
};
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(dataAdapter);
Now on item selected in spinner put below
selectedItem = position;
Here is solution via XML:
Spinner looks like:
<Spinner
android:id="@+id/settingsSleepingTimePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/spinner_main_button"
android:popupBackground="@color/colorPrimary"
android:textColor="@android:color/white"
android:textSize="20sp"/>
While creating spinner set setDropDownViewResource as custom layout:
adapter.setDropDownViewResource(R.layout.spinner_item);
And spinner_item.xml looks like:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/spinner"
android:textColor="#ffffff"
android:textSize="20sp" />
And finally we set @drawable/spinner like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/colorPrimaryLight" android:state_hovered="true" />
<item android:drawable="@color/colorPrimaryLight" android:state_selected="true" />
</selector>
Hope my answer will be helpfull!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With