Change text color of selected item in spinner
Asked Answered
C

14

43

How can I change the font color of the selected item in a spinner?

I am able to change the background color of the selected item, the color of the dropdown item etc, but not the text color of selected item... how can I do that?

my code is: this is spinner i am using--:

<Spinner
                android:id="@+id/spinner1"
                android:layout_width="wrap_content"
                android:layout_height="32dip"
                android:background="@drawable/mybg"
                android:divider="@drawable/list_divider"
                android:drawSelectorOnTop="true"
                android:popupBackground="#D3D5D3"
                android:prompt="@string/activityy_prompt" 
                />

this is mybg.xml

<!-- <item android:drawable="@drawable/blue" android:state_pressed="false"/> -->
<!-- <item android:drawable="@drawable/back11"/> -->

<item android:drawable="@drawable/greenyellow1" android:state_focused="true" android:state_pressed="false"/>
<item android:drawable="@drawable/greenyellow1" android:state_focused="true" android:state_pressed="true"/>
<item android:drawable="@drawable/greenyellow1" android:state_focused="false" android:state_pressed="true"/>
<item android:drawable="@drawable/greenyellow1" android:state_selected="true"/>
<item android:drawable="@drawable/back11"/>

using these i am not able to change the text color of selecetd item...

Chose answered 13/3, 2013 at 8:2 Comment(3)
use this link , it will help #7584658Genocide
feed us the code which you tried.No coin No CallLongoria
@user1283633 i follow this link and able to change background color only.... not able to change text color...Chose
W
18

drawable/mybg:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_activated="true">
        <color android:color="@color/black" />
    </item>
</layer-list>

This will change the selected item color in the popup.

Witt answered 18/6, 2013 at 8:3 Comment(1)
change android:drawable="@color/red"Sharell
R
84

Define OnItemSelectedListener like this:

  private AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(0x00000000);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };

and then Set OnItemSelectedListener to spinner like this:

spinner.setOnItemSelectedListener(listener);
Repel answered 13/3, 2013 at 8:27 Comment(2)
Thx... its working .. earlier it was not working but now its working may be because i add few line in manifest file like.... android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"Chose
This might cause a little lag on setting the default selection's color. See my answer here which fixes that problem: #9477165Selectee
P
19

You can change the selected text color by adding OnItemSelectedListener to the spinner

qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        ((TextView) view).setTextColor(Color.BLACK); //Change selected text color
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
});
Plumbo answered 9/2, 2017 at 9:12 Comment(3)
Excellent! Add this to change the text size while you are at it: ((TextView) view).setTextSize(30f);Enamel
Works really well programmatically! Thank you!Putrid
Unfortunately there appears to be a lag where you can see the color switch from the default to the new one.Milkmaid
W
18

drawable/mybg:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_activated="true">
        <color android:color="@color/black" />
    </item>
</layer-list>

This will change the selected item color in the popup.

Witt answered 18/6, 2013 at 8:3 Comment(1)
change android:drawable="@color/red"Sharell
F
17

try implementing onItemSelected in your OnItemSelectedListener for change the text color of spinner selected item

public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 
    int index = adapterView.getSelectedItemPosition();
    ((TextView) spinner.getSelectedView()).setTextColor(getResources().getColor(R.color.Blue)); //<----
Flabbergast answered 8/5, 2014 at 5:15 Comment(0)
P
7

using selector as text color .

create color_selector.xml in drawable like

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:color="#000000" /> <!-- pressed -->
     <item android:state_focused="true"
           android:color="#000000" /> <!-- focused -->
     <item android:color="#FFFFFF" /> <!-- default -->
 </selector>

and in textview

<TextView 
   android:textColor="@drawable/color_selector"/>
Pixie answered 13/3, 2013 at 8:11 Comment(5)
weird. here nothing related to background, all you need to do is use android:textColor=""@drawable/color_selector" with view contains text (spinner/textView) .Pixie
is there property textcolor for spinner??Chose
hopefully. else you will need to use textview along with spinner for this approach.Pixie
This is much elegant solution.Ablation
i use it , and when run app , app crashPrecontract
S
4

just use this line onItemSelected listner -

public void onItemSelected(AdapterView<?> parent, View arg1, int arg2,long arg3) 
     {

       item = (String) parent.getItemAtPosition(arg2);


       ((TextView) parent.getChildAt(0)).setTextColor(0x00000000);

 }
Safekeeping answered 2/12, 2015 at 6:29 Comment(0)
P
4

Setting ((TextView) view).setTextColor(getResources().getColor(R.color.black)); inside onItemSelected(...) listener method will work. It sets color for your selected spinner text.

Parthen answered 8/11, 2018 at 10:34 Comment(0)
D
3

If your spinner is using an ArrayAdapter, you can simply pass a custom layout for your spinner items. That layout can be a simple textView but with the android:textColor attribute.

MainActivity.java onCreate()

adapter = new ArrayAdapter<>(this, R.layout.spinner_custom_textcolor, data);
spinner.setAdapter(adapter);

spinner_custom_textcolor.xml

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

*Everything from the above layout except for android:textColor is a direct copy from android.R.layout.simple_spinner_item

Doralyn answered 15/6, 2016 at 2:49 Comment(0)
S
2

some of you that using MaterialBetterSpinner and Binding your Layouts, all the above won't help, try this, hope it helps you:

public class MyAdapter extends ArrayAdapter<String> {      

        public MyAdapter(Context context, int textViewResourceId, List<String> objects) {
            super(context, textViewResourceId, objects);           

        }

        @Override
        public View getDropDownView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }

        public View getCustomView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final YourXMLBinding rowBinding = DataBindingUtil.inflate(inflater, R.layout.yourXML, parent,false);
            rowBinding.tv1.setText(mMy.getValues().get(position));
            if(position == mMy.getCurrentIndex()) {
                rowBinding.tv1.setTypeface(Typer.set(getContext()).getFont(Font.ROBOTO_BOLD));//change font
                rowBinding.tv1.setTextColor(ContextCompat.getColor(getContext(), R.color.yourColor));//change color
            }
            return rowBinding.getRoot();
        }
    }

yourXML is something like this:

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="@color/colorBackgroundStart">
        <TextView
            android:id="@+id/tv1"
            android:layout_width="0dp"
            android:layout_weight="0.7"
            android:layout_height="30dp"
            android:textColor="#fff"
            android:textSize="16dp"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="10dp"
            android:layout_marginLeft="8dp"/>

</layout>

create a spinner with this adapter and yourXML :

final MyAdapter adapter = new MyAdapter(getContext(), R.layout.yourXML, s.getValues());

final MaterialBetterSpinner spinner = new MaterialBetterSpinner(getContext());
spinner.setAdapter(adapter);
Struma answered 4/7, 2017 at 5:36 Comment(0)
D
2

I know this is old question, but I had big problem on changing color of selected item in spinner in TabLayout and this really worked for me:

spinner.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ((TextView) spinner.getSelectedView()).setTextColor(Color.WHITE); //change to your color
            }
        });
Disparity answered 21/1, 2018 at 17:37 Comment(0)
D
0
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
      @Override
      public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
           ((TextView) adapterView.getChildAt(0)).setTextColor(Color.WHITE);
}
Dambro answered 24/10, 2017 at 7:42 Comment(0)
H
0

The solution that worked for me was to use a CheckedTextView for the the drop down resource view and then change the color of the checked item using a color selector.

spinner_dropdown_item.xml in the layout folder:

<?xml version="1.0" encoding="utf-8"?>

<!-- A `CheckedTextView` allows the color of the text to be changed when it is selected (checked). -->
<CheckedTextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/spinner_item_textview"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:maxLines="1"
    android:ellipsize="end"
    android:paddingStart="20dp"
    android:paddingEnd="20dp"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:textSize="18sp"
    android:textColor="@color/spinner_color_selector"
    android:background="@color/spinner_background" />

spinner_color_selector in the color folder:

<?xml version="1.0" encoding="utf-8"?>

<!-- Highlight the selected (checked) item when the spinner is open. -->
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_checked="true" android:color="@color/white" />
    <item android:color="@color/blue_100" />
</selector>

spinner_dropdown_item.xml must be set as the DropDownResourceView for the Adapter. In my case I am using a ResourceArrayAdapter that pulls information from multiple sources.

// Setup a `MatrixCursor` for the static entries.
String[] matrixCursorColumnNames = {DatabaseHelper._ID, DatabaseHelper.NAME};
MatrixCursor matrixCursor = new MatrixCursor(matrixCursorColumnNames);
matrixCursor.addRow(new Object[]{-2, getString(R.string.first_spinner_item)});
matrixCursor.addRow(new Object[]{-1, getString(R.string.second_spinner_item)});

// Get a `Cursor` with the list of additional items from the database.
Cursor cursor = DatabaseHelper.getCursor();

// Combine `matrixCursor` and `cursor`.
MergeCursor mergeCursor = new MergeCursor(new Cursor[]{matrixCursor, foldersCursor});

// Create a `ResourceCursorAdapter` for the spinner with `this` context.  `0` specifies no flags.;
ResourceCursorAdapter resourceCursorAdapter = new ResourceCursorAdapter(this, R.layout.spinner_item, mergeCursor, 0) {
    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        // Get a handle for the spinner item `TextView`.
        TextView spinnerItemTextView = (TextView) view.findViewById(R.id.spinner_item_textview);

        // Set the `TextView` to display the name.
        spinnerItemTextView.setText(cursor.getString(cursor.getColumnIndex(DatabaseHelper.NAME)));
    }
};

// Set the `ResourceCursorAdapter` drop drown view resource.
resourceCursorAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);

// Get a handle for the `Spinner`.
Spinner spinner = (Spinner) findViewById(R.id.spinner);

// Set the adapter for the folder `Spinner`.
spinner.setAdapter(resourceCursorAdapter);

Because ResourceCursorAdapter uses the same bindView to populate the spinner when it is open and closed, the id of the TextView in spinner_dropdown_item.xml and spinner_item.xml must be the same.

spinner_item.xml in the layout folder:

<?xml version="1.0" encoding="utf-8"?>

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/spinner_item_textview"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:maxLines="1"
    android:ellipsize="end"
    android:paddingStart="10dp"
    android:paddingEnd="10dp"
    android:textSize="18sp"
    android:textColor="@color/primaryTextColor" />
Hagerman answered 24/10, 2017 at 8:16 Comment(0)
S
-1

See my answer to a similar question here. My answer is similar to Priya's, except it properly sets the default selected item's text color as well (so there's no lag with the wrong color when waiting for the spinner to automatically select the default item, which occurs after the user interface is already on-screen).

Selectee answered 25/11, 2015 at 9:5 Comment(0)
S
-1

You don't need java code for background color change in Android 2.3v. Just add android:background="#F0F8FF" to your spinner in xml file.

Souther answered 25/4, 2017 at 6:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.