In the process of development, often in order to beautify the interface needs, will modify the default appearance of the button, and because the Android button has three states-default, is clicked, is selected. So, if you want to change the appearance of the button, you need to make changes to these three situations, perhaps in the past, we are most likely to think of is the manual monitoring of button selection and click events, and then write code to replace the background of the button, but in Android, we do not need this trouble, Android has long been a good solution for us, that is selector resources. If we want to implement the three background of the button, we just need to create such an XML file in the res/drawable directory:
Selector.xml
?
56789 |
<selector xmlns:android=
"http://schemas.android.com/apk/res/android"
>
<item android:state_window_focused=
"false"
android:drawable=
"@drawable/t3"
/>
<item android:state_focused=
"true"
android:drawable=
"@drawable/t1"
/>
<item android:state_pressed=
"true"
android:drawable=
"@drawable/t2"
/>
<item android:drawable=
"@drawable/t3"
/>
</selector>
|
As described in the resource file above, we define three different image resources for each of these behaviors, and then we just need to specify the background resource as drawable/selector in the corresponding button, and we'll do everything we need to do.
1 |
<ImageButton android:layout_width= "100px" android:layout_height= "50px" android:src= "@drawable/selector" /> |
This is all so simple, not to write any logic code, Android development is not very convenient ~, the following is :
Default:
Click:
Selected:
Android ImageButton after clicking the button before the button color changes