Android Style

透過Style動態控制 UI

李建毅 (Joe Lee) 2018/10/02 10:00:00
1152

透過Style動態控制 UI


簡介

透過Style 動態變更 Android UI 樣式, 透過selector標籤動態變更UI 樣式

作者

李建毅 (Joe Lee)


selector標籤

  selector標籤,可以添加一個或多個item子標籤,而相應的狀態是在item標籤中定義的。定義的xml文件可以作為兩種資源使用:drawable和color。作為drawable資源使用時,一般和shape一樣放於 drawable 目錄下,item必須指定 android:drawable 屬性;作為color資源使用時,則放於 color 目錄下,item必須指定 android:color 屬性。
 
  • android:state_enabled :設置觸摸或點擊事件是否可用狀態,一般只在false時設置該屬性,表示不可用狀態
  • android:state_pressed :設置是否按壓狀態,一般在true時設置該屬性,表示已按壓狀態,默認為false
  • android:state_selected :設置是否選中狀態,true表示已選中,false表示未選中
  • android:state_checked :設置是否勾選狀態,主要用於CheckBox和RadioButton,true表示已被勾選,false表示未被勾選
  • android:state_checkable :設置勾選是否可用狀態,類似state_enabled,只是state_enabled會影響觸摸或點擊事件,而state_checkable影響勾選事件
  • android:state_focused :設置是否獲得焦點狀態,true表示獲得焦點,默認為false,表示未獲得焦點
  • android:state_window_focused :設置當前窗口是否獲得焦點狀態,true表示獲得焦點,false表示未獲得焦點,例如拉下通知欄或彈出對話框時,當前界面就會失去焦點;另外,ListView的ListItem獲得焦點時也會觸發true狀態,可以理解為當前窗口就是ListItem本身
  • android:state_activated :設置是否被激活狀態,true表示被激活,false表示未激活,API Level 11及以上才支持,可通過代碼調用控件的setActivated(boolean)方法設置是否激活該控件
  • android:state_hovered :設置是否鼠標在上面滑動的狀態,true表示鼠標在上面滑動,默認為false,API Level 14及以上才支持

 範例程式 

1. UI layout 


<Button
android:text="1"
android:id="@+id/keyboard_num1"
android:background="@drawable/keyboard_button_indicator">
</Button>

drawable selector  keyboard_button_indicator.xml

 

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<!-- android:state_focused是被焦點 -->
<item android:drawable="@drawable/keyboard_button_selected" android:state_focused="true"></item>
<!-- android:state_pressed是被點擊 -->
<item android:drawable="@drawable/keyboard_button_selected" android:state_pressed="true"></item>
<!-- 默認時的背景圖片 -->
<item android:drawable="@drawable/keyboard_button_default"></item>
</selector>

drawable keyboard_button_default.xml


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<!-- 圓形內部的填充顏色 -->
<solid android:color="#56000000"></solid>
<!-- 環狀外部寬度的顏色 -->
<stroke android:width="1dp" android:color="#99ffffff"></stroke>
</shape>

drawable keyboard_button_selected.xml

 

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<!-- 圓形內部的填充顏色 -->
<solid android:color="#56ffffff"></solid>
<!-- 環狀外部寬度的顏色 -->
<stroke android:width="1dp" android:color="#56ffffff"></stroke>
</shape>
李建毅 (Joe Lee)