0

I am very new in Android programming. I am trying to make a spinner whose items have different background colors, but I couldn't find any understandable information. Could you write me a solution with detailed explanation?

This is my addcourse class:

public class Addcourse extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.addcourse);

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

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.color_array, android.R.layout.simple_spinner_item);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spinner.setAdapter(adapter);    
}

I have the colors in colors.xml And my spinner:

<Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
akjoshi
  • 15,374
  • 13
  • 103
  • 121
evis
  • 137
  • 1
  • 11

1 Answers1

1

You need to provide your own ListAdapter, such as a subclass of ArrayAdapter that returns views with the background color set. See here for an example that changes the color of the text:

android change text color of items in spinner

You can instead just call super and set the background color and return that.

ArrayAdapter<CharSequence> adapter = new ArrayAdapter(this, R.array.color_array, android.R.layout.simple_spinner_item) {
  public View getDropDownView(int position, View convertView, ViewGroup parent){
    View view = super.getDropwDownView(position, convertView, parent);
    int color = 0xFFFFFF; //white or use Color.argb(...)
    //change color according to position the way you want
    view.setBackgroundColor(color);
    return view;
  }
};
Community
  • 1
  • 1
Mattias Isegran Bergander
  • 11,811
  • 2
  • 41
  • 49
  • I get error at ViewGroup and setBackground How can I fix it? And yes, color depends on position, so every item will have a different color. Can I specify the color inside this class (Ex: using #0000FF), not with reference to color.xml ? – evis Dec 25 '12 at 19:00
  • use `setBackgroundColor()` instead. Updated the answer – Mattias Isegran Bergander Dec 25 '12 at 20:09
  • 1
    I did exactly like that, but the spinner gives no choices...or I am missing something? – evis Dec 25 '12 at 20:45