Android: each spinner element is a different color

I have a spinner where I would like the text of each item to be a different color. for example, on item0, the text should be red, item1 should be blue, and item2 should be green. I tried to set the item I want to change to a textView and change the color of the textbox, but it doesn't work that way. any ideas on how to accomplish this task?

              Spinner spinner = (Spinner) findViewById(R.id.spinner1);

              ArrayList<String> array = new ArrayList<String>();
              array.add("item0");
    array.add("item1");
    array.add("item2");

              ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,R.layout.row, array);
              spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

               spinner.setAdapter(spinnerArrayAdapter)

              try{
    TextView tv = new TextView((Context) spinner.getItemAtPosition(0));
    tv.setTextColor(Color.argb(0, 255, 0, 0));  
    }catch(Exception e){
    Toast.makeText(getApplicationContext(), "Error: " + e.toString(), Toast.LENGTH_LONG);
        }

      

+2


source to share


1 answer


create your own class that extends BaseAdapter and implements SpinnerAdapter.

Override getDropDownView and when handling position you can format the text image from the custom layout you inflate.



@Override
public View getDropDownView(int position, View convertView, ViewGroup parent){

    View v = convertView;

    if (v == null) {
        LayoutInflater vi = (LayoutInflater) mContext
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.your_custom_layout, null);
    }
    TextView tv=(TextView) v.findViewById(R.id.yourTextViewFromYourLayout);
    tv.setText(yourArrayList.getItem(position));
    switch (position) {
case 0:
 //set tv color here...
 break;
case 1:
 //set tv color here...
etc...
default:
 //set default color or whatever...
}       
        return v;
    }

      

+5


source







All Articles