標籤:android blog http ar color 使用 sp on 檔案
我們做過項目的或多或少做過類似這樣的一個功能:當點擊某個組件後,組件的背景改變。初學者往往是這麼一個思路:給組件設定一個監聽器,當監聽到事件的時候,改變組件的狀態(背景圖片或者背景色)。當然,這種做法是完全正確的,但是當組件特別多的時候,要處理的代碼很多,很繁瑣,android提供了一個selector(選取器)來改變介面的狀態。下面我們以改變一個button背景來介紹它的具體用法。
1.因為selector是在Drawable檔案夾下配置的,所以首先在Drawable檔案夾下建立一個android xml檔案
2.然後在button_selector.xml中添加以下代碼
//被按下的背景
<item android:state_pressed="true"
android:drawable="@drawable/cancel_small_click"/>
//獲得焦點時的背景
<item android:state_focused="true"
android:drawable="@drawable/cancel_small_unclick"/>
//預設時的背景
<item android:drawable="@drawable/cancel_small_unclick" />
3.最後,使用這個xml檔案,有兩種方式:
(1)第一種是在組件中配置:android background=“@drawable/button_selector"即可實現
(2)第二種是在代碼中使用:Drawable drawable = getResources().getDrawable(R.drawable.button_selector); Button.setSelector(drawable)
注1:列表設定selector後有可能顯示為黑,需要加上android:cacheColorHint="@android:color/transparent"
注2:Button的selector還有其他的效果
android:state_selected是選中
android:state_focused是獲得焦點
android:state_pressed是點擊
android:state_enabled是設定是否響應事件,指所有事件
根據這些狀態同樣可以設定button的selector效果。也可以設定selector改變button中的文字狀態。以下就是配置button中的文字效果:drawable/button_font.xml
當然Button還可以實現更複雜的效果
結伴旅遊,一個免費的交友網站:www.jieberu.com
推推族,免費得門票,遊景區:www.tuituizu.com
Android之selector的使用