利用selector設置ImageButton不同狀態下的背景圖片

在Android中,控件Button和ImageButton一般有三種狀態:常態(normal)、點擊狀態(pressed)、聚焦狀態(focused)。很多時候,我們爲了提高用戶的體驗常常爲Button以及ImageButton的不同狀態設置不同的背景圖片,下面介紹一種利用selector設置Button和ImageButton不同狀態下的背景圖片的方法。

具體步驟如下:

一、在res/drawable文件下創建selector.xml,示例代碼如下:

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

二、編寫佈局文件,爲佈局文件中的ImageButton設置selector,示例代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  	android:layout_height="wrap_content"
  	android:layout_width="fill_parent">
	<ImageButton
		android:id="@+id/title_IB"
		android:layout_height="wrap_content"
		android:layout_width="wrap_content"
		android:background="#00000000"
		android:layout_marginRight="4dp"
		android:layout_centerVertical="true"
		android:src="@drawable/selector">
	</ImageButton>
</RelativeLayout>

到此就爲ImageButton的不同狀態設置了不同的背景圖片。

THE END!



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章