編輯:初階開發
在 Android 中,Button 的視覺回饋不必靠程式碼判斷。透過在 drawable 目錄定義一份 selector XML,就能讓同一顆按鈕依焦點與按下狀態自動換圖。
以 Button 為例,它有三種狀態:focused(取得焦點)、pressed(被按下)與 default(一般)。步驟是先寫 selector 檔,再在版面配置中參照它。
<?XML version="1.0" encoding="UTF-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item
android:state_focused="true"
android:state_pressed="false"
android:drawable="@drawable/focused" />
<item
android:state_focused="true"
android:state_pressed="true"
android:drawable="@drawable/focusedpressed" />
<item
android:state_focused="false"
android:state_pressed="true"
android:drawable="@drawable/pressed" />
<item
android:drawable="@drawable/default" />
</selector>
<ImageButton
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/btnselector"
android:background="#00000000" />
注意 android:src 的值是 selector 檔名 btnselector,而不是某一張具體的圖片。
res/drawable/search_button.xml:
<?XML version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="false"
android:drawable="@drawable/search_normal" />
<item android:state_focused="true" android:state_pressed="true"
android:drawable="@drawable/search_click" />
<item android:state_focused="false" android:state_pressed="true"
android:drawable="@drawable/search_click" />
<item android:state_enabled="false"
android:drawable="@drawable/search_disable" />
<item android:drawable="@drawable/search_normal" />
</selector>
res/layout/main.xml:
<ImageButton
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/entry"
android:layout_toRightOf="@id/history_search"
android:layout_gravity="center"
android:layout_marginTop="2px"
android:background="@drawable/search_button" />
這裡多了一個 state_enabled="false",讓按鈕在不可用時顯示灰階圖。selector 的判定順序是由上而下,因此要把最明確的狀態放在前面,並把沒有任何條件的項目留到最後作為預設值。
Android 特色開發:帳戶管理(AccountManager)實作解析
本文節選自機械工業出版社《Android 應用開發揭秘》,作者楊豐盛。該書涵蓋 Android 框架、組件、使用者介面、遊戲開發、資料儲存、多媒體與網路開發等基礎,並深入
Android Gallery 控件詳解:圖片瀏覽與自定義 ImageAdapter 實作
Gallery 是 Android 裡專門用來做「圖片瀏覽」的控件,用手指滑動就能在頭尾相連的圖片序列中切換。用法和 ListView 同一套路:在版面裡擺好 Galle
Android 快捷方式(二):讓自己的 Activity 出現在 Launcher 選單裡
在桌面空白處長按,會跳出「加到主畫面」的對話框,接著選擇「捷徑」,系統便会列出所有可建立捷徑的 Activity——每個項目顯示對應應用的圖示與名稱。 問題是:怎麼讓自
Android 執行緒間通信:Handler 與 Looper
Android 提供 Handler 與 Looper 來處理執行緒間的訊息溝通。例如子執行緒從網路下載圖片後,可透過綁定在主執行緒的 Handler 發送訊息,讓 UI