Android之selector的使用

來源:互聯網
上載者:User

標籤: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的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.