Fustigador Fustigador - 1 month ago 22
Android Question

Change Spinner background programmatically

I have some Spinners that need to change the background. So, I have this xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/iconodesplegableactivar"
android:state_enabled="true"/>
<item android:drawable="@drawable/iconodesplegable"
android:state_enabled="false" android:state_window_focused="false"/>
</selector>


I have no problems with the Spinners set in layout file, but some spinners are generated dynamically.

How could I use that xml in a spinner generated dinamically? The setBackground() method doesn't allow you to set xml as an argument, and I can't add an ID to the XML.

Thank you!

Answer

Taken From this answer, and something which I'm using as well:

If you're creating Spinner dynamically then use this:

// to change background of the popup list
  spinner.setPopupBackgroundResource(R.drawable.spinner_background);

// to change the `Spinner` background
  spinner.setBackgroundResource(R.drawable.your_drawable);

And here is spinner_background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#ffffff" />
</shape>
Comments