此代码用于动态创建 Button。问题是我想设置背景颜色并设置背景 Drawables。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke android:width="1px" android:color="#696969"/>
</shape>
这是我想设置按钮背景颜色的类,然后我想使用我的 Drawable。
Button btnTag = new Button(alltable.this);
btnTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
try {
btnTag.setWidth(130);
btnTag.setBackground(getResources().getDrawable(R.color.blue));
} catch (Exception e){
e.printStackTrace();
}
最佳答案
在 drawable(如 files_bg.xml)文件夹中创建一个资源并将其设置为布局的背景。
在图层列表中使用两项,一项用于形状中的纯色,另一项用于位图。
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/totalFilesBgColor" />
</shape>
</item>
<item>
<bitmap
android:src="@drawable/bg_icon"
android:tileMode="disabled" />
</item>
</layer-list>
现在将可绘制对象设置为布局中或您使用它的任何地方的背景。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/files_bg">
</LinearLayout>
关于android - 在 Android 中设置背景颜色并使用 Drawable 作为背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34289223/