Android根據Button狀態(normal,focused,pressed)顯示不同背景圖片
Android中Button 有focused, selected, pressed 等不同狀態,通過配置一個XML格式的 drawable "selector" 即可實現”在不同狀態下顯示不同背景圖片“的功能。1. 在res/drawable目錄下添加一個xml文件,用來描述Button在不同狀態下對應的不同圖片。我這裏給該xml文件命名為btn_background.xml
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@drawable/btn_pressed"
/>
<!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/btn_normal"
/>
<!-- focused -->
<item android:drawable="@drawable/btn_normal"
/>
<!-- default -->
</selector>
2. 在res/layout目錄下,對應的layout xml文件中,將Button的android:background屬性設置為btn_background即可。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/btn_background"
/>
</LinearLayout>
3.運行結果
默認狀態(unselected)
點擊狀態(pressed)
最後更新:2017-04-02 06:51:46