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();
}
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>
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With