-1

I want to create effects for ImageButton. For example, it will change color when clicked...How I do it? I want to do this in .xml file. Can you help me! Thank you! I tried to create the state.xml file as follwing:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item
    android:state_pressed="true"
    android:state_enabled="true"
    android:drawable="@drawable/btn_0" />
<item
    android:state_focused="true"
    android:state_enabled="true"
    android:drawable="@drawable/btn_ac" />

</selector>

However, I can't set background for ImageButton. The error like this: enter image description here

Robotic Vn
  • 437
  • 2
  • 7
  • 20
  • Hi, check this [answer](http://stackoverflow.com/questions/4755871/how-to-set-image-button-backgroundimage-for-different-state) maybe it's what your are looking for – medhdj Jan 24 '15 at 17:03

2 Answers2

2

All you have to do it to add the "android:background" attribut to your ImageButton and set a drawable.

Your layout

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/my_btn"
    android:background="@drawable/btn_drawable"/>

btn_drawable.xml

    <selector xmlns:android="http://schemas.android.com/apk/res/android">

        <item android:state_pressed="true"
              android:drawable="@drawable/blue"
              />
        <item android:state_focused="true"
              android:drawable="@drawable/white"
              />
<item android:drawable="@drawable/green" />
    </selector>

In that code above you set a different drawable when your ImageButton is pressed (state_pressed), focused (state_focus) or when is normal (not pressed and not focused).

Here you can find with more detail.

1

Create a drawable like below and name it as btn_drawable.

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

    </selector>

This is for an example,Like this you can add the <item/> according to your needs and state of the image button. Then set the drawable as image button background.

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/btn_drawable"/>
Remees M Syde
  • 2,564
  • 1
  • 19
  • 42
  • Thanks for your help. However, I still can't set background for ImageButton. btn_drawable doesn't appear in background list, so I can't choose. Can you help me! Thank you! – Robotic Vn Jan 24 '15 at 18:11