android - 通过 xml 文件以编程方式设置背景

标签 android drawable setbackground

我的 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/

相关文章:

android - 在另一个 Layout.xml 和 Activity 上设置背景资源

android - 移除 readonly 属性并更改类型并在单个事件中关注相同的输入字段

android - LOCAL_LDLIBS 不起作用,但 LOCAL_LDFLAGS 起作用。为什么?

android - 如何在 Kotlin 中绘制可绘制对象?

java - 无法设置 JPanel 颜色和 JRadioButton 不可见性

ios - 在 UIButton 中,setImage 和 setBackgroudnImage content id 不同,它旋转了 90 度

Android - CardView 高程阴影变暗

android - 葫芦测试设置,ANDROID_HOME 路径

android - 中性可绘制文件夹中应放置哪种图像尺寸?

Android多渐变xml