问题描述
我在 drawable 中有一个 xml 文件,它看起来像:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/green_button_unchecked" android:state_pressed="true"/>
<!-- pressed -->
<item android:drawable="@color/green_button_unchecked" android:state_focused="true"/>
<!-- focused -->
<item android:drawable="@color/green_button_unchecked" android:state_selected="true"/>
<!-- selected -->
<item android:drawable="@color/gray_6"/>
<!-- default -->
</selector>
我可以在 setBackgroundResource(drawable.xmlName) 中使用它;
我们知道,setBackgroundResource() 需要 int 类型的 resouceId...
如果不允许我使用资源,我如何通过以编程方式创建 xml 来使用 setBackgroundResource() ??
我希望你理解我的问题... 谢谢你
解决方法
我不确定你是如何以编程方式创建 XML 的,就像你想创建一个 Drawable 一样,你可以在不需要 XML 的情况下做到这一点。
任何 XML 文件都有一个名称,IDE 会创建一个生成的类,其中包含文件的所有 ID。
如果是可绘制对象,则为 R.drawable
。
对于颜色,它是 R.color
。
对于字符串 R.string
。
所以如果你想按资源设置背景,你只需使用setBackgroundResource(R.drawable.file_name)
如果您不想使用 XML,则必须手动创建 Drawable 对象,并改用 setBackground
或 setBackgroundDrawable
。这是一个很大的麻烦,因为有很多类型的 Drawable。
矢量可绘制、渐变可绘制、分层可绘制、颜色可绘制等
您必须弄清楚自己想要什么并手动创建