设置背景颜色,并在Android中使用drawable作为背景

Usm*_*sif 5 android button android-layout

<?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>
Run Code Online (Sandbox Code Playgroud)

此代码用于动态创建按钮,问题是我想设置背景颜色并设置背景可绘制对象。

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();
}
Run Code Online (Sandbox Code Playgroud)

这是一类,我想设置btn的背景色,然后使用我的drawable。

kj0*_*007 7

在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> 
Run Code Online (Sandbox Code Playgroud)

现在将drwable设置为在布局中或使用的任何位置的bakcground。

<LinearLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:background="@drawable/files_bg">

 </LinearLayout>
Run Code Online (Sandbox Code Playgroud)


Pra*_*ath 6

这个文件(rectangle.xml)放在你的drawable文件夹中。

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
<solid android:color="#FF4081"/>
</shape>
Run Code Online (Sandbox Code Playgroud)

修改代码中的这一行。

btnTag.setBackground(getResources().getDrawable(R.drawable.rectangle,null));\\API level 21 and higher, otherwise
 getResources().getDrawable(R.drawable.rectangle).
Run Code Online (Sandbox Code Playgroud)


adr*_*oir 5

有点晚了,但我遇到了同样的问题,我按照下面的描述解决了它。

首先获取你的绘图:

Drawable d = getResources().getDrawable(R.drawable.shape_rectangle);
Run Code Online (Sandbox Code Playgroud)

然后应用您的自定义颜色:

d.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
Run Code Online (Sandbox Code Playgroud)

然后将其设置为视图/按钮的背景:

btn.setBackground(d);
Run Code Online (Sandbox Code Playgroud)