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

Android 自定義 Button:用 selector 做出按下回饋,再綁上動畫

系統內建的元件用久了總是長得差不多,既不符合品牌調性,也難給使用者「按下去有反應」的明確回饋。自定義 Button 其實不難,核心是一個 selector 描述檔。

版面:多一行的 background

在 AbsoluteLayout 中放五顆 Button,其中四顆是自定義樣式,另一顆用來觸發動畫。自定義的部分看起來只多了一個屬性:

<Button
    android:id="@+id/bt1"
    android:layout_x="0dp"
    android:layout_y="100dp"
    android:text="@string/bt1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/bt_define" />

關鍵:res/drawable/bt_define.xml

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

    <item android:drawable="@drawable/bt"
          android:state_enabled="true"
          android:state_focused="true"
          android:state_pressed="false" />

    <item android:drawable="@drawable/bt_bg"
          android:state_enabled="true"
          android:state_pressed="true" />

    <item android:drawable="@drawable/bt_bg"
          android:state_checked="true"
          android:state_enabled="true" />

    <item android:drawable="@drawable/bt" />

</selector>

這份描述檔的意義是:正常狀態顯示 bt,一旦按下或取得焦點就換成 bt_bg。若只塞一張圖當 background,按下去完全沒有視覺變化,使用者會不確定有沒有點到。最後那個沒有 state 的項目是預設值,必須放在最後,否則會吃掉前面的比對。

加上動畫

在 res 下建立 anim 資料夾,分別放四組描述檔:淡入淡出(alpha)、位移(translate)、旋轉(rotate)與縮放(scale)。在 Activity 中取得控制項後,用 AnimationUtils.loadAnimation() 載入並呼叫 startAnimation() 即可。

bt1.startAnimation(AnimationUtils.loadAnimation(this, R.anim.alpha1));
bt2.startAnimation(AnimationUtils.loadAnimation(this, R.anim.translate2));
bt3.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate3));
bt4.startAnimation(AnimationUtils.loadAnimation(this, R.anim.scale4));

延伸方向

selector 除了 state_pressed 與 state_focused,還可用 state_enabled、state_checked、state_selected 組合出更細緻的狀態;搭配 shape 標籤甚至能純 XML 畫出圓角與漸層,完全不需要圖片素材。真正複雜的效果,就留給自己日後慢慢摸索了。

Copyright © Linux教程網 All Rights Reserved