android: each item of spinner different color
I have a spinner in which I would like to have the text of each item be a different color. for example on item0 the text should be red, item1 the text sho开发者_运维问答uld be blue, and item2 the text should be green. I tried setting the item I want to change to a textView and changing the color of the textview but it does not work that way. any ideas on how to acomplish 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);
}
create your own class that extends BaseAdapter and implements SpinnerAdapter.
Override getDropDownView, and as you process the position you can format the textview from a 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's color here...
break;
case 1:
//set tv's color here...
etc...
default:
//set default color or whatever...
}
return v;
}
精彩评论