teekib
teekib

Reputation: 2821

Android: how to give alternate colors to the spinner items

I have a spinner with the items as below

ArrayAdapter<Message> arrayadapter = new ArrayAdapter<Message>(activity, android.R.layout.simple_spinner_item, messages);
                arrayadapter.setDropDownViewResource(R.layout.textview);

i want to give altenate colors to the listitems.how can i do that.Any help is appreciated

Upvotes: 1

Views: 1167

Answers (3)

itsrajesh4uguys
itsrajesh4uguys

Reputation: 4638

Hi You can use the following code

 @Override
       public View getDropDownView(int position, View convertView, ViewGroup parent){
            View v = convertView;
            if (v == null) {
               Context mContext = this.getContext();
               LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.row, null);
         } 
    TextView tv=(TextView) v.findViewById(R.id.spinnerTarget);
    tv.setText(testarray.get(position));
    switch (position) {
    case 0:  tv.setTextColor(Color.RED);  
    break; 
    case 1:  tv.setTextColor(Color.BLUE);
    break;
    default:  tv.setTextColor(Color.BLACK);
    break;
    }
return v;  
              }              
       };     
       pSpinner.setAdapter(spinnerAdapter); 
} 

Upvotes: 0

Chirag Patel
Chirag Patel

Reputation: 11508

You can use

ArrayAdapter<CharSequence> adapter =
    new ArrayAdapter(this, R.layout.simple_spinner_item, myList) {
    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        View view = super.getDropDownView(position, convertView, parent);
        if (position % 2 == 0) { // we're on an even row
           view.setBackgroundColor(evenColor);
        } else {
           view.setBackgroundColor(oddColor);
        }
       return view;
    }
}

Upvotes: 2

Related Questions