Android - customize background color of Button

Android allows you to customize the background color of a Button. You can have different background colors as the Button is in normal state and press state. To accomplish this task, you will follow the steps below:

1. Create a new Android project in Eclipse ADT.

2. Look for the Activity_Main.xml file. You will modify the file to add a button as shown below.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >

   <Button
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Button"
     android:background="@drawable/btstate"
     />

</RelativeLayout>


3. Create a colors.xml file to define two color values. One color is for normal state and another one for press state. The content of the colors.xml file is shown below. It must be saved in the res/values folder.

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <drawable name="normal_color">#0B6121</drawable>
<drawable name="select_color">#00BFFF</drawable>
</resources>

4. Create btstate.xml file to define a selector resource that will be used as the background of the button. You need to save this file in res/drawable folder. The btstate.xml file defines a selector that has two items. One item is for press state. It uses select_color value. Another item is for normal state that uses normal_color value.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:drawable="@drawable/select_color" android:state_pressed="true" />
   <item android:drawable="@drawable/normal_color"/>
</selector>

5. Run the project

Customize-background-color-of-Button

Posted by: Dara | post date: 05-05-2014 | 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.