Chaning Android Button Background style using Selectors Example

Android provides selectors that help you change the button styles depending on various states like, pressed, normal, disabled.
You can easily customize button in android using selectors. Here I will demonstrate how you can do that.


1. First make a layout with a button.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/imgBtnSelector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/custom_button" />

</LinearLayout>





2. Make button for different states Normal, focused and pressed state. You can also choose a different button for just any one of the states. Here i have created just two buttons. For focused state it will be the same as Normal state.




Focused - Displays when button is focused using keypad or otherwise.
Normal -   Displays normally
Pressed - Displays when button is pressed


3. This is the important part, here we will be making XML file (custom_button.xml) in res/drawable folder.
You can make different files and keep according to the device resolution in drawable-hdpi, drawable-mdpi, drawable-ldpi.

The custom_button.xml file-

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

Remember that this must be the order of the different states of buttons, otherwise it will not work. This custom_button.xml file must be set as background to android:button, we've already done it in the main layout.

android:background="@drawable/selector_button" />

4. Now in the MainActivity.java just add the button and the layout and you are done.
I have not used a focusable mode, but if you want a different respone for focusable then you will need to set if focusable like this imageButton1.setFocusableInTouchMode(true);

public class MainActivity extends Activity {
Button imageButton;
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  imageButton = (Button) findViewById(R.id.imageButtonSelector);
 }
 }

If you have any questions feel free to comment them below.
Learn how to add background Image to button with text overlayed-Adding background image and text properly. 

Comments