Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set background color and use Drawable as background in Android

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();
}
like image 756
Usman Asif Avatar asked Dec 15 '15 12:12

Usman Asif


2 Answers

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>
like image 81
kj007 Avatar answered Oct 06 '22 12:10

kj007


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).
like image 37
Prathap Badavath Avatar answered Oct 06 '22 13:10

Prathap Badavath