Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 讓 Button 點擊時文字同步變色

編輯:關於 Android 程式設計

Button 的點擊效果本來是件小事。當 UI 設計告訴我「點擊時文字顏色也要跟著背景一起變」時,我第一反應居然是請他切兩張圖給我——後來想想實在不太靠譜,於是好好研究了一下怎麼用純 XML 做出文字變色, WITHOUT 動用任何一張圖片。

關鍵在於:顏色選擇器(color selector)並不是只能放在 res/color 底下用 <color> 標籤定義,也可以改用 <drawable> 標籤宣告,如此一來就能被當成 android:textColor 的值使用。以下分三步完成。

步驟一:在 colors 資源中定義色值

注意這裡用的標籤是 drawable 而不是一般的 color,這正是讓它能被 textColor 引用的關鍵:

<drawable name="color_red">#fffa3d39</drawable>
<drawable name="color_green">#ff00adba</drawable>
<drawable name="color_gray">#fff4f4f8</drawable>

步驟二:建立 selector 檔案

寫法與一般的 selector 幾乎相同,唯一的差別是把 android:drawable 換成 android:color,並引用上一步定義的顏色。把它放在 res/color/ 目錄下,例如 button_text_color.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item
        android:state_focused="false"
        android:state_enabled="true"
        android:state_pressed="false"
        android:color="@drawable/color_red" />
    <item
        android:state_enabled="false"
        android:color="@drawable/color_gray" />
    <item
        android:state_pressed="true"
        android:color="@drawable/color_green" />
    <item
        android:state_focused="true"
        android:color="@drawable/color_red" />
</selector>

步驟三:在佈局中套用

把第二步寫好的檔案指定給 android:textColor 即可:

<Button
    android:id="@+id/btn_submit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="提交"
    android:textColor="@color/button_text_color" />

幾點實務提醒

selector 中 item 的撰寫順序會影響結果:系統由前而後比對,第一個符合條件的項目就會被採用。因此像 state_enabled="false" 這類「最嚴格」的條件通常要放在前面,否則禁用狀態可能被其他規則蓋掉。

另外,這個技巧不只適用於 Button,凡是支援 android:textColor 的元件——TextView、RadioButton、CheckBox,甚至自訂 View——都能沿用同一份 selector。比起切兩張圖,純 XML 的做法不僅省下圖片資源與流量,換色時也只要改一個色值,維護成本遠低於圖片替換。

以上就是本篇的全部內容,希望對你有所幫助!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved