evis
evis

Reputation: 137

Spinner with different background colors

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" />

Upvotes: 0

Views: 2114

Answers (1)

Mattias Isegran Bergander
Mattias Isegran Bergander

Reputation: 11909

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;
  }
};

Upvotes: 1

Related Questions