我的 xml 布局中有一个 ImageButton
:
<ImageButton android:id="@+id/tabsButton"
android:background="@drawable/button" android:layout_height="48dp"
android:layout_width="48dp"></ImageButton>
如您所见,我在这里设置了 ImageButton 的背景:
android:background="@drawable/button"
其中button是我放在drawable文件夹下的一个xml文件,下面是button.xml的代码:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/duscrollover" /> <!-- pressed -->
<item android:drawable="@android:color/transparent" /> <!-- default -->
</selector>
到现在为止,一切都很好并且工作正常,但现在我想在创建时以编程方式设置我的 ImageButton 的背景,所以我这样做了:
View myView = findViewById(R.id.tabsButton);
myView.setBackgroundResource(R.drawable.button);
但是,它无法识别 myView.setBackgroundResource(R.drawable.button) 中的按钮 那么如何获取放置在 drawable 文件夹中的 xml 文件的引用呢?
提前致谢
最佳答案
您是否遇到找不到资源的错误?如果是这样,请尝试清理项目并重新运行。
关于android - 通过 xml 文件以编程方式设置背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9385170/