Java – Android spinner has a different background for each line
•
Java
I know this topic has been solved many times. I have found several such problems, but I can't meet my needs I want a list of colors in the spinner I did, but my spinner was empty
In my oncreate():
spinner = (Spinner) findViewById(R.id.spinner1); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this,R.array.androidcolors,android.R.layout.simple_spinner_item); adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter);
In the folder value, I created a file colors xml:
<resources> <item name="blue" type="color">#FF33B5E5</item> <item name="purple" type="color">#FFAA66CC</item> <item name="green" type="color">#FF99CC00</item> <item name="orange" type="color">#FFFFBB33</item> <item name="red" type="color">#FFFF4444</item> <item name="darkblue" type="color">#FF0099CC</item> <item name="darkpurple" type="color">#FF9933CC</item> <item name="darkgreen" type="color">#FF669900</item> <item name="darkorange" type="color">#FFFF8800</item> <item name="darkred" type="color">#FFCC0000</item> <integer-array name="androidcolors"> <item>@color/blue</item> <item>@color/purple</item> <item>@color/green</item> <item>@color/orange</item> <item>@color/red</item> <item>@color/darkblue</item> <item>@color/darkpurple</item> <item>@color/darkgreen</item> <item>@color/darkorange</item> <item>@color/darkred</item> </integer-array> </resources>
Solution
It's simple. You have to do it
1. Write your own custom adapter for the spinner. How do you do this
class SpinnerAdapter extends BaseAdapter { ArrayList<Integer> colors; Context context; public SpinnerAdapter(Context context) { this.context=context; colors=new ArrayList<Integer>(); int retrieve []=context.getResources().getIntArray(R.array.androidColors); for(int re:retrieve) { colors.add(re); } } @Override public int getCount() { return colors.size(); } @Override public Object getItem(int arg0) { return colors.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int pos,View view,ViewGroup parent) { LayoutInflater inflater=LayoutInflater.from(context); view=inflater.inflate(android.R.layout.simple_spinner_dropdown_item,null); TextView txv=(TextView)view.findViewById(android.R.id.text1); txv.setBackgroundColor(colors.get(pos)); txv.setTextSize(20f); txv.setText("Text "+pos); return view; } }
2. Set the adapter like this
spnColors=(Spinner)findViewById(R.id.spnColor); spnColors.setAdapter(new SpinnerAdapter(this));
The end result is
Please accept the answer if it helps!
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码