以编程方式更改 Spinner 背景

Change Spinner background programmatically

我有一些微调器需要更改背景。所以,我有这个 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>

我在布局文件中设置的微调器没有问题,但有些微调器是动态生成的。

如何在动态生成的微调器中使用 xml? setBackground() 方法不允许您将 xml 设置为参数,并且我无法将 ID 添加到 XML.

谢谢!

摘自 this answer,以及我正在使用的东西:

如果您要动态创建 Spinner 然后使用这个:

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

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

这里是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>

请使用setBackgroundResource(R.drawable.your_file_name)将资源设置为背景。此方法未被弃用。希望对您有所帮助!

写下你的代码:

spinner.setBackgroundResource(R.drawable.spinner_background);

添加一个LinearLayout 作为它的背景。

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/YOUR_BACKGROUND_COLOR">

        <Spinner
            android:id="@+id/pattern_spinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
</LinearLayout>