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

Android 控制項美化:Shape 自定義圖形的使用方法

編輯:關於 Android 程式設計

如果你覺得 Android 系統自帶的 UI 控制項不夠美觀,可以嘗試自定義控制項。以 Button 為例,除了使用 drawable 圖片之外,今天要介紹的是透過自定義圖形 shape 來美化控制項。Android 支援 shape、gradient、stroke、corners 等多種屬性。

以下以系統 Button 的 selector 為例,說明各屬性的用途:

<shape>
    <gradient
        android:startColor="#ff8c00"
        android:endColor="#FFFFFF"
        android:angle="270" />
    <stroke
        android:width="2dp"
        android:color="#dcdcdc" />
    <corners
        android:radius="2dp" />
    <padding
        android:left="10dp"
        android:top="10dp"
        android:right="10dp"
        android:bottom="10dp" />
</shape>

各屬性含義如下:gradient 為漸層,其中 startColor 是起始顏色、endColor 是結束顏色、angle 是角度;stroke 可理解為邊框;corners 為圓角,其中的 radius 是圓角半徑;最後 padding 是內容的相對內距。

而一個 Button 完整的 selector 定義,可以針對不同狀態(按下、獲得焦點等)分別設定不同的 shape:

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <gradient android:startColor="#ffc2b7" android:endColor="#ffc2b7" android:angle="270" />
            <stroke android:width="2dp" android:color="#dcdcdc" />
            <corners android:radius="2dp" />
            <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" />
        </shape>
    </item>
    <item android:state_focused="true">
        <shape>
            <gradient android:startColor="#ff9d77" android:endColor="#ff9d77" android:angle="270" />
            <stroke android:width="2dp" android:color="#fad3cf" />
            <corners android:radius="2dp" />
            <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" />
        </shape>
    </item>
</selector>

要留意的是,這幾個 item 的差別主要體現在 state_pressed(按下)與 state_focused(獲得焦點)狀態下顯示的樣式;而沒有加上 state 屬性的 item,則可視為常規(預設)狀態下的外觀。透過這種方式,就能為按鈕打造豐富的視覺回饋效果。

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