xydev
xydev

Reputation: 3409

What should I use ImageButton or Button?

i have a button with two states(selected and unselected). the image of button is different for the states. Which one should I use? How do i set images and states? Please give suggestions(i am new to android).

Upvotes: 10

Views: 4882

Answers (1)

Impression
Impression

Reputation: 727

Use an xml configuration within the drawable folder. Instead of referencing the image as background for your button, you reference this xml configuration (file name):

E.g: my_button.xml

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

<item
    android:state_focused="true"
    android:state_pressed="false"
    android:drawable="@drawable/button_style1_active" />
<item
    android:state_focused="true"
    android:state_pressed="true"
    android:drawable="@drawable/button_style1_down" />
<item
    android:state_focused="false"
    android:state_pressed="true"
    android:drawable="@drawable/button_style1_down" />
<item
    android:drawable="@drawable/button_style1_up" />

</selector>

Use in layout.xml:

<Button android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Tap me" 
        android:background="@drawable/my_button"/>

With this configuration you can influence the appearance of the button, when pressed, focused and so on. Its the same way for both types of buttons (Button and ImageButton). If your button contains no text, use ImageButton.

Upvotes: 14

Related Questions