在Android中设置背景颜色并使用Drawable作为背景 [英] Set background color and use Drawable as background in Android
本文介绍了在Android中设置背景颜色并使用Drawable作为背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码用于动态创建 Button.问题是我想设置背景颜色并设置背景Drawables.
This code is used to create a Button dynamically. The problem is that I want to set background color and also set a background 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.
This is the class I want to set the background color of a Button and then I want use my 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)文件夹中创建一个资源并将其设置为布局背景.
Create a resource in drawable (like files_bg.xml) folder and set it as background for layout.
在图层列表中使用两项,一项用于形状纯色,另一项用于位图.
Use two item in layer list, one for solid color in shape and other one bitmap.
<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>
现在将 drawable 设置为布局中的背景或您使用它的任何地方.
and now set drawable as background in layout or wherever you are using it.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/files_bg">
</LinearLayout>
这篇关于在Android中设置背景颜色并使用Drawable作为背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文