Mahendra Liya
Mahendra Liya

Reputation: 13218

Android Change Text Color of Spinner (displayed text - not items in spinner)

Except for one screen, the Spinner needs to have 'black' text. The one screen requires Spinner to have 'White' color (both displayed text for the selected item and spinner items).

Here is the image for better clarity. top image is how it appears in black color and the bottom is the spinner items image with white text color

I'm able to get 'White' color for spinner items but not the selected displayed text. Again, I don't want to globally change the styling - just this one screen. Is this possible?

Upvotes: 4

Views: 3153

Answers (2)

Serge
Serge

Reputation: 328

When you creating Spinner you have to provide it with adapter. If you were using standart implementation from android developers:

 Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.planets_array, android.R.layout.simple_spinner_item);

Than what you can do is to create your own layout that for representing selected item text that is provided as and put it inside adapter and there you can provide 'textColor' atribute, something like this:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@android:id/text1"
      style="?android:attr/spinnerItemStyle"
      android:singleLine="true"
      android:textColor="@color/primary_blue"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:ellipsize="marquee"
      android:textAlignment="inherit"/>

If you are using ArrayAdapter.createFromResource() don't forget to have TextView with android:id="@android:id/text1" so this adapter will be able to bind data to your layout.

Upvotes: 0

Max77
Max77

Reputation: 1566

public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 
    int index = adapterView.getSelectedItemPosition();
    ((TextView) spinner.getSelectedView()).setTextColor(getResources().getColor(R.color.white));
}

Upvotes: 5

Related Questions