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

Android shape 標籤入門:圓角、邊框與填充色一次搞定

編輯:關於 Android 開發

Android shape 標籤入門:圓角、邊框與填充色一次搞定

先看看系統預設的 EditText 與 Button 長什麼樣子:

加上自訂 shape 之後,效果變成這樣:

簡單講,shape 可以替元件加上背景、邊框、圓角等樣式,也能搭配 selector 做出按下時的狀態變化。

定義檔放在 drawable 目錄下,命名為 shape_xxx.xml。

一、EditText 用的定義

<?xml version="1.0" encoding="utf-8"?>
<!-- shape 類型:rectangle 矩形、oval 橢圓、line 直線、ring 環形 -->
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <!-- 四角圓角半徑 -->
    <corners android:radius="5dp" />
    <!-- 內邊距 -->
    <padding android:left="5dp" android:top="6dp"
             android:right="5dp" android:bottom="6dp" />
    <!-- 填充色 -->
    <solid android:color="#FFFAE3" />
    <!-- 邊框:需要邊框才加 -->
    <stroke android:width="1dp" android:color="#87CEFA" />
</shape>

二、Button 用的定義

寫法完全相同,只是參數值不同:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="8dp" />
    <padding android:left="3dp" android:top="5dp"
             android:right="3dp" android:bottom="5dp" />
    <solid android:color="#09A3DC" />
    <stroke android:width="1dp" android:color="#88000000" />
</shape>

三、在布局中引用

透過 background 屬性掛上去即可:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="@drawable/shape_et"
        android:hint="請輸入用戶名" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:background="@drawable/shape_btn"
        android:text="確定"
        android:textColor="#ffffff" />
</LinearLayout>

幾個實務提醒:

· corners 想只對特定角設圓角,可以用 topLeftRadius、topRightRadius、bottomLeftRadius、bottomRightRadius 分別指定。

· stroke 的 color 支援 #88000000 這種帶 alpha 的寫法,做出半透明邊框很有效果。

· 自訂 background 之後,Button 就不會再有系統預設的點擊回饋。若需要按下的視覺變化,請再寫一個 selector 指向正常態與按壓態兩個 shape。

· shape 也能用 gradient 做漸層、用 size 固定尺寸,或直接當作 View 的背景畫出分隔線。

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