Android style button programmatically

There are different ways to apply styles to a Button. You can apply the styles to the Button using xml file or using Java code. If styles of the Button can be changed at run-time, applying the style programmatically is the better choice.

Now to have an example application on applying style programmatically to the Button, in Android Studio, you create a new project. Then in the activity_main.xml file, you add a Button.


Then in the res/values, you create colors.xml file. In the colors.xml file, you define two drawable color objects for states of the Button.

<?xml version="1.0" encoding="utf-8"?>

   <drawable name="bt_normal_color">#08088A</drawable>
   <drawable name="bt_press_color">#00BFFF</drawable>


In the res/drawable directory, you create bt_style.xml file. In the bt_style.xml file, you define two items. The first item represents the style of the Button when it is pressed and the second item is the style of the Button in the normal state.

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="">

   <item android:state_pressed="true">

        <gradient android:angle="90" android:startColor="@drawable/bt_press_color" android:endColor="@drawable/bt_normal_color" />
        <padding android:bottom="5dp" android:left="5dp" android:right="5dp" android:top="5dp" />
        <corners android:radius="10dp"/>

        <gradient android:angle="90" android:startColor="@drawable/bt_normal_color" android:endColor="@drawable/bt_press_color"/>
        <padding android:bottom="5dp" android:left="5dp" android:right="5dp" android:top="5dp" />
        <corners android:radius="10dp"/>


Now to read styles defined in the bt_style.xml file and apply them to the Button programmatically, in onCreate() method of the MainActivty class, you write code as shown below.

     Button bt=(Button)findViewById(;
     bt.setBackgroundResource( R.drawable.bt_style);


Posted by: Dara | post date: 02-14-2015 | Subject: Android Apps Development

write programming tip

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.