Set background color and use Drawable as background in Android

36,784

Solution 1

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> 

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>

Solution 2

This file(rectangle.xml ) put in your drawable folder.

<?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>

modify this line in your code.

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

Solution 3

A bit late but I had the same problem and I solved it like it's described bellow.

First get your drawable:

Drawable d = getResources().getDrawable(R.drawable.shape_rectangle);

Then apply your custom color to it:

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

Then set it as background to your view/button:

btn.setBackground(d);

Solution 4

This work for me

<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>
Share:
36,784
Usman Asif
Author by

Usman Asif

Updated on July 28, 2022

Comments

  • Usman Asif
    Usman Asif almost 2 years

    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>
    

    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();
    }