我有一些需要改变背景的Spinners。所以,我有这个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>
我对布局文件中设置的Spinners没有任何问题,但是一些微调器是动态生成的。
我如何在动态生成的微调器中使用该xml? setBackground()方法不允许您将xml设置为参数,并且我无法向XML添加ID。
谢谢!
答案 0 :(得分:8)
取自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>
答案 1 :(得分:3)
添加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>
答案 2 :(得分:1)
请使用setBackgroundResource(R.drawable.your_file_name)
将资源设置为背景。不推荐使用此方法。我希望这有帮助!
答案 3 :(得分:0)
写入您的代码:
spinner.setBackgroundResource(R.drawable.spinner_background);