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

设置背景颜色,并在android中使用drawable作为背景,android,android-layout,button,Android,Android Layout,Button,这是我想设置btn背景颜色的类,然后我想使用我的可绘制文件。此文件(rectangle.xml)放在您的可绘制文件夹中 Button btnTag = new Button(alltable.this); btnTag.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP

这是我想设置btn背景颜色的类,然后我想使用我的可绘制文件。

此文件(rectangle.xml)放在您的可绘制文件夹中

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)文件夹中创建一个资源,并将其设置为布局的背景

在图层列表中使用两个项目,一个用于形状中的纯色,另一个用于位图

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

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

<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>
然后对其应用自定义颜色:

Drawable d = getResources().getDrawable(R.drawable.shape_rectangle);
然后将其设置为视图/按钮的背景:

d.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);

您可以创建新的可绘制图形,并将其指定给背景。 i、 e

这是我的工作


Drawable drawable = new GradientDrawable();
drawable.shape = GradientDrawable.RECTANGLE;
drawable.setStroke(Utils.toPx(1), Color.parseColor("#696969") );
btnTag.setBackground(drawable);


“android:background”应该可以在这里使用。它需要
“@color/…”
@drawable/…”
参数使用多层可绘制参数,然后请清除您的答案@piotrek1543抱歉,我不知道您已经在使用
btnTag.setBackground(getResources().getDrawable(R.color.blue));
通过这种方法,您也可以使用可绘制(R.drawable.LOGO)如果要为整个布局设置背景颜色,请转到布局xml文件并设置主布局
android:background
属性
d.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
btn.setBackground(d);

Drawable drawable = new GradientDrawable();
drawable.shape = GradientDrawable.RECTANGLE;
drawable.setStroke(Utils.toPx(1), Color.parseColor("#696969") );
btnTag.setBackground(drawable);
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape android:shape="rectangle">
        <solid android:color="@color/appColor" />
        <corners android:radius="@dimen/spacing_small"/>
    </shape>
   </item>
     <item android:drawable="@drawable/add_white"/>
</layer-list>