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

android:shape 的使用詳解教程

編輯:關於 Android 程式設計

在 Android 中,我們常用 shape 來定義控件的一些顯示屬性。今天研究了一下 shape 的用法,對它有了大體的認識,這裡做個整理。先看下面這段代碼:

<shape>
    <!-- 實心 -->
    <solid android:color="#ff9d77"/>
    <!-- 漸變 -->
    <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>

solid:實心填充

solid 就是填充的意思,透過 android:color 指定填充的顏色。

gradient:漸變

android:startColor 與 android:endColor 分別為起始色與結束色,android:angle 是漸變角度,必須為 45 的整數倍。此外,漸變預設模式為 android:type="linear"(線性漸變),也可指定為徑向漸變 android:type="radial",此時需要額外指定半徑 android:gradientRadius="50"。

stroke:描邊

android:width 是描邊寬度,android:color 是描邊顏色。我們還可以把描邊做成虛線,設定方式為 android:dashWidth="5dp" 與 android:dashGap="3dp",其中 dashWidth 表示一段橫線的寬度,dashGap 表示間隔的距離。

corners:圓角

android:radius 為角的弧度,數值越大角越圓。我們還可以把四個角設成不同的角度,方法如下:

<corners
    android:topRightRadius="20dp"    <!--右上角-->
    android:bottomLeftRadius="20dp"  <!--右下角-->
    android:topLeftRadius="1dp"      <!--左上角-->
    android:bottomRightRadius="0dp"  <!--左下角-->
/>

這裡有個地方要特別注意:bottomLeftRadius 其實對應的是右下角,而非左下角,千萬別搞錯了。另外,網上有人說設成 0dp 無效,但我在 2.2 上測試發現是可以的,可能該版本已修復了這個問題;若真的無效,那就只能設成 1dp 了。

padding:間隔

padding 用來設定內間隔,這個在 XML 佈局檔中經常用到,就不多贅述了。

應用示例

大體上就是這樣。實務中,shape 常用在 Selector 裡作為 Button 的背景,分別定義按鈕的一般狀態、獲得焦點狀態與按下時的狀態。做法是在 button_selector.xml 中用 selector 搭配多個 item,每個 item 引用一個 shape 定義,再在佈局中把 Button 的 background 指向這個 selector 即可,如此便能為按鈕打造豐富的視覺回饋效果。

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