编程更改Spinner背景

3

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

我在布局文件中使用Spinner设置没有问题,但是有些Spinner是动态生成的。

如何在动态生成的Spinner中使用xml?setBackground()方法不允许将xml作为参数设置,并且我无法为xml添加ID。

谢谢!


使用 setBackgroundResource(R.drawable.your_file_name); - Malwinder Singh
2
不是这样的。请查看:http://developer.android.com/reference/android/view/View.html#setBackgroundResource(int)。 - Malwinder Singh
@Fustigador setBackgroundDrawable() 方法已被弃用,请使用 setBackgroundResource() 方法。 - Sharp Edge
你是对的,我的错。setBackgroundDrawable() 是过时的方法。抱歉。 - Fustigador
4个回答

10

摘自这个答案,也是我正在使用的内容:

如果你要动态创建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>

2
似乎很不直观,必须创建一个XML文件才能告诉控件绘制背景颜色。我并不是说你错了,而是安卓的这个领域似乎过于复杂了。可能是因为API太薄弱了? - ComeIn
1
如果你在Android开发过程中没有撞墙或拔头发,那么你做错了lol。 - Sharp Edge
@Journey,现在建议您至少支持API 16,而不是低于它。根据Android官方操作系统市场份额,只有0.14%的设备仍在使用低于API 16的版本。 - Sharp Edge
我正在更新一款已经在Play Store上的会计应用程序,超过50%的用户使用API 16或以下版本。无论如何,感谢您提供的信息。 - Niraj Niroula

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>

1
请使用setBackgroundResource(R.drawable.your_file_name)来将资源设置为背景。该方法尚未过时。希望这可以帮到你!

0

请在您的代码中编写:

spinner.setBackgroundResource(R.drawable.spinner_background);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接