Wednesday, January 14, 2015

How to change Button background color programmatically in Android

activity_main.xml code snippet

<Button
 android:id ="@+id/push_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:text="Button Solid Background"
 android:padding="15dp"
 android:onClick="perform_action"
 />
MainActivity.java code snippet

public void perform_action(View v)
{
 Button btn = (Button) findViewById(R.id.push_button);
 //set the button background from drawable resource xml file
 btn.setBackground(getResources().getDrawable(R.drawable.button_bg_solid));
}
Imported Class

import android.view.View;
import android.widget.Button;
res/drawable/button_bg_solid.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape android:shape="rectangle">
        <solid android:color="#BC8F8F"/>
        <stroke android:color="#8B4513" android:width="2dp"/>
    </shape>
</item>
</selector>
More android examples