简体   繁体   中英

Is it possible to give every spinner item a different color

In an alertdialog I have a spinner with color codes:

Spinner cSpinner = (Spinner)mView.findViewById(R.id.spinner_c);
ArrayAdapter<String> cadapter = new ArrayAdapter<String>(Cal_main.this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.colorspin));
cadapter.setDropDownViewResource(R.layout.custom_spinner_items);
cSpinner.setAdapter(cadapter);

The color array:

<string-array name="colorspin">
        <item>#f44336</item>
        <item>#d32f2f</item>
        <item>#e91e63</item>
        <item>#c2185b</item>
        <item>#9c27b0</item>
</string-array>

If it is possible, what is the best way to set the background of each item to the array colors?

Yes, it is.

the array and spinner:

    String[] colors = getResources().getStringArray(R.array.colorspin);

    //Getting the instance of Spinner and applying OnItemSelectedListener on it
    Spinner spin = (Spinner) mView.findViewById(R.id.spinner_c);

    SpinnerColorAdapter spincAdapter = new SpinnerColorAdapter(getApplicationContext(),colors);
    spin.setAdapter(spincAdapter);

    spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  //Performing action onItemSelected and onNothing selected
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
        String color = colors[position].toString();
        tvStep.setText(color);

        Toast.makeText(getApplicationContext(), color, Toast.LENGTH_LONG).show();
    }

The SpinnerColorAdapter:

public class SpinnerColorAdapter extends BaseAdapter {
Context context;
String[] Colors;
LayoutInflater inflter;

public SpinnerColorAdapter(Context applicationContext,  String[] Colors) {
    this.context = applicationContext;
    this.Colors = Colors;
    inflter = (LayoutInflater.from(applicationContext));
}

//@Override
public int getCount() {
    return Colors.length;
}

//@Override
public Object getItem(int i) {
    return null;
}

//@Override
public long getItemId(int i) {
    return 0;
}

//@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    view = inflter.inflate(R.layout.spinner_row, null);
    Button colorbtn = (Button) view.findViewById(R.id.btn_indexcolor);
    colorbtn.setBackgroundColor(Color.parseColor(Colors[i]));
    TextView colorview = (TextView) view.findViewById(R.id.indexcolor);

    return view;
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM