I\'m implementing a simple method to add a Button
to a LinearLayout
programatically.
When I invoke the setBackground(Drawable background) metho
<Button
android:id="@+id/btnregister"
android:layout_width="150dp"
android:layout_height="45dp"
android:layout_gravity="center"
android:layout_marginHorizontal="10dp"
android:layout_marginVertical="20dp"
android:paddingVertical="5dp"
style="@style/btn_register"
android:text="Register"
android:textColor="#FFFFFF" />
apply below code in Styles.xml file :
<style name="btn_register">
<item name="android:layout_marginTop">15dp</item>
<item name="android:backgroundTint">#009688</item>
<item name="cornerRadius">20dp</item>
</style>
You might be testing on an API below level 16 (Jelly Bean).
The setBackground method is only available from that API level onwards.
I would try with setBackgroundDrawable (deprecated) or setBackgroundResource if that's the case.
For instance:
Drawable d = getResources().getDrawable(R.drawable.ic_launcher);
Button one = new Button(this);
// mediocre
one.setBackgroundDrawable(d);
Button two = new Button(this);
// better
two.setBackgroundResource(R.drawable.ic_launcher);
To create a homogeneous background for a View, you can create a drawable resource of type shape, and use that with the setBackgroundResource.
red_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#FF0000"/>
</shape>
Activity:
Button b = (Button)findViewById(R.id.myButton);
b.setBackgroundResource(R.drawable.red_background);
But this will look pretty bad, flat and out of place. If you want a colored button that looks like a button, than you can either design it yourself (rounded corners, stroke, gradient fill...) or a fast and dirty solution is to add a PorterDuff filter to the button's background:
Button b = (Button)findViewById(R.id.myButton);
PorterDuffColorFilter redFilter = new PorterDuffColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
b.getBackground().setColorFilter(redFilter);
Since after Android 16 , the setBackgroundDrawable is deprecated, I suggested to checked before set code
you need to check current version of Android also
Button bProfile; // your Button
Bitmap bitmap; // your bitmap
if(android.os.Build.VERSION.SDK_INT < 16) {
bProfile.setBackgroundDrawable(new BitmapDrawable(getResources(), bitmap));
}
else {
bProfile.setBackground(new BitmapDrawable(getResources(),bitmap));
}
You can't use setBackground()
.
This method may be not available in your Android level.