Android點擊按鈕切換背景效果-selector使用方法

來源:互聯網
上載者:User

標籤:

有時候我們要實現“按下按鈕和釋放按鈕時,按鈕的背景圖片(顏色)不同”的效果,我們可以用selector實現

1.編寫XML代碼:
在項目的res/drawable目錄下建立xml檔案,添加相關代碼:

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_pressed="true"          android:drawable="@drawable/button_pressed" /> <!--按下後的背景圖片 -->    <item android:drawable="@drawable/button_normal" /> <!-- 預設的背景圖片  --></selector>
View Code


當然在該目錄下要放入相關圖片。

 

各屬性解釋:

android:state_pressed 是否按下,如一個按鈕觸摸或者點擊。
android:state_focused 是否取得焦點,比如使用者選擇了一個文字框。
android:state_hovered 游標是否懸停,通常與focused state相同,它是4.0的新特性
android:state_selected 被選中,它與focus state並不完全一樣,如一個list view 被選中的時候,它裡面的各個子組件可能通過方向鍵,被選中了。
android:state_checkable 組件是否能被check。如:RadioButton是可以被check的。
android:state_checked 被checked了,如:一個RadioButton可以被check了。
android:state_enabled 能夠接受觸摸或者點擊事件
android:state_activated 被啟用android:state_window_focused 應用程式是否在前台,當有通知欄被拉下來或者一個對話方塊彈出的時候應用程式就不在前台了

 

 

2.在要設定此效果的Button的布局檔案中添加:

<Button    android:layout_height="wrap_content"    android:layout_width="wrap_content"    android:background="@drawable/button" />

 

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.