Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android state list drawable 各項 state 屬性一次講清楚

用 XML 定義 drawable 時,可以讓同一張圖片在不同狀態下顯示不同外觀。以 Button 為例,它有 pressed、focused 等狀態,透過 state list drawable,就能為每種狀態指定各自的圖片。

先看一個範例

XML 檔案存放於 res/drawable/button.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:state_enabled="true"
          android:state_window_focused="false"
          android:drawable="@drawable/button_pressed" />  <!-- pressed、enable 等多個屬性可並用 -->
    <item android:state_focused="true"
          android:drawable="@drawable/button_focused" />  <!-- focused -->
    <item android:state_hovered="true"
          android:drawable="@drawable/button_focused" />  <!-- hovered -->
    <item android:drawable="@drawable/button_normal" />       <!-- default -->
</selector>

接著在版面配置中把它套用到 Button 上:

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

屬性逐一說明

android:drawable:指定要套用的 drawable 資源。

android:state_pressed:是否被按下,例如按鈕被觸摸或點擊。

android:state_focused:是否取得焦點,例如使用者選中了某個文字框。

android:state_hovered:游標是否懸停其上,通常與 focused 狀態一致,是 4.0 才新增的特性。

android:state_selected:是否被選中。它與 focus 狀態並不完全相同,例如 ListView 被選中時,其內部子元件可能是透過方向鍵而被「選中」。

android:state_checkable:元件是否可被勾選,例如 RadioButton 就是可勾選的。

android:state_checked:是否已被勾選,例如某個 RadioButton 被選中。

android:state_enabled:是否能接受觸摸或點擊事件。

android:state_activated:是否處於啟用(activated)狀態。

android:state_window_focused:應用程式是否位於前景。當通知列被拉下或彈出對話框時,應用程式就不再處於前景。

比對規則要注意

如果 selector 裡有多個 item,系統會由上而下逐一比對,取第一個符合者,並不是挑「最合適」的那一個。因此把最明確的條件放在前面、把 default 放在最後,是比較穩妥的寫法。另外,若某個 item 完全沒有標註任何狀態,它就能被任何狀態比對到——這正是上面範例中 button_normal 的作用。

更詳細的說明可參考官方 API 文件:https://developer.android.com/guide/topics/resources/drawable-resource.html#StateList

Copyright © Linux教程網 All Rights Reserved