Customizing spinner's item background color

允我心安 提交于 2019-12-11 08:25:34

问题


I am making an app to calculate resistor value out of its color bands. Everything works fine on the pure programming side. At the moment for selcting color bands I am using a spinner filled with list of colors.

I really want to make it look better. I want to be able to set background color of each item in the spinner to its corresponding color:

What should I do to achive this? Here is part of my code:

Array used for spinner:

  <string-array name="FourBandResistorFullColor">
    <item>Black</item>
    <item>Brown</item>
    <item>Red</item>
    <item>Orange</item>
    <item>Yellow</item>
    <item>Green</item>
    <item>Blue</item>
    <item>Violet</item>
    <item>Gray</item>
    <item>White</item>    
  </string-array>

Adapter code in OnCreate method:

    var bandOne = FindViewById<Spinner>(Resource.Id.bandOneColor);
    var bandOneAdapter = ArrayAdapter.CreateFromResource(this, Resource.Array.FourBandResistorFullColor,
                                                         Android.Resource.Layout.SimpleSpinnerItem);
    bandOneAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
    bandOne.Adapter = bandOneAdapter;
    bandOne.ItemSelected += BandOne_ItemSelected;

回答1:


You need to use a custom adapter. I guess you are using an ArrayAdapter? If so you could do it like so:

    private class MyArrayAdapter extends ArrayAdapter<String>{

        public MyArrayAdapter(Context context, int textViewResourceId) {
            super(context, textViewResourceId); 
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            int color = getColorFromName(getItem(position));
            view.setBackgroundColor(color);
            return view;
        }   
    }

Note that getColorFromName is a function you would need to implement yourself. It maps from String to an int color value (ARGB). Red for exmaple would be 0xffff0000.



来源:https://stackoverflow.com/questions/10374675/customizing-spinners-item-background-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!