casolorz casolorz - 1 year ago 71
Android Question

How can I change the color of the selected spinner item using XML not Java?

I have an Android

Spinner
and the dropdown colors are all working ok but I can't change the text color of the selected item using XML, not Java. I've tried everything I could think of. Below is my code:

<android.support.v7.widget.AppCompatSpinner
android:layout_width="368dp"
android:layout_height="wrap_content"
android:entries="@array/test"
style="@style/dropdown_text"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="8dp"></android.support.v7.widget.AppCompatSpinner>


Here are all the things I've tried with style:

<style name="dropdown_text">
<item name="android:background">#000000</item>
<item name="android:textColor">#ffffff</item>
<item name="android:textColorPrimary">#ffffff</item>
<item name="android:textColorSecondary">#ffffff</item>
<item name="android:textAppearance">@style/white_text</item>
</style>

<style name="white_text">
<item name="android:textColor">#ffffff</item>
</style>


The background color works just fine but not the text color.

So how can I change the selected item text color?

Thanks.

Edit: I know there are tons of posts asking this same thing, the majority of them say to do it in Java code but I want to do it on XML. Also some show the styles you have to change but I've tried all their suggestions and nothing has worked.

Answer Source

When you populate your Spinner with entries, AppCompatSpinner will create an ArrayAdapter and use android.R.layout.simple_spinner_item as your "selected" view. simple_spinner_item is a TextView styled using spinnerItemStyle.

<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@android:id/text1"
    style="?android:attr/spinnerItemStyle"
    android:singleLine="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ellipsize="marquee"
    android:textAlignment="inherit"/>

So, if you want to change the text color in simple_spinner_item, you'll need to supply your own style for spinnerItemStyle. Something like:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:spinnerItemStyle">@style/YourSpinnerItemStyle</item>
</style>

<style name="YourSpinnerItemStyle" parent="Widget.AppCompat.TextView.SpinnerItem">
    <item name="android:textColor">@android:color/white</item>
</style>

You could also use textAppearance instead of textColor.

Results:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download