Search code examples
javaandroidbackgroundspinnerandroid-spinner

Java Android Spinner Item Background Color


I want to change the color of an item in a string array / Spinner, but I can't get it to work.

I also found this topic and it seems to be the thing I need:
Customizing spinner's item background color

I tried to implement it (not just copy paste) but it didn't work.

Can someone help me maybe how to implement it the "right way" (I'm not that experienced in Android/Java)

Can't I just do something (easier) like this?

<string-array name="test">
   <item android:backgroundcolor="#08FF00">green</item>
   <item android:backgroundcolor="#FF0000">red</item>
</string-array>

I appreciate any help!


Solution

  • The adapter from Customizing spinner's item background color is precisely what you need. Of course, you need to implement a method returning the desired color for each item of the array.

    If your input is the color name (i.e., this spinner acts a color picker, you could use Color.parseColor(). It supports some named colors, plus numeric values.

    Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception. Supported formats are: #RRGGBB #AARRGGBB 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuschia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'