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

為 Android 的 View 加上上下左右邊框:shape 的做法

編輯:關於 Android 程式設計

場景

開發時常會遇到表格式的版面配置,這時候邊框怎麼處理?

如果只需要一條線,做法很單純:丟一個 TextView,把寬或高固定為 1dp~2dp,另一維度設成 match_parent,再給個背景色即可。線的粗細由寬高決定,顏色就是設定的背景色。

但若是四邊都要線,一條一條拼接未免太費工。有兩種解法:一是準備一張帶邊線的 9-patch 圖片;二是自己寫一個 shape 版面,需要時透過 background 屬性引用。以下說明第二種。

第一步:定義 shape

新增 res/drawable/shape_textview_cart.xml:

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

    <!-- 四邊邊框 -->
    <stroke
        android:width="1dp"
        android:color="#ebebeb" />

    <!-- 若要指定各邊不同粗細,改用 inset 或拆成多層 drawable -->

</shape>

若需要上下左右各自獨立控制,可在 stroke 之外搭配 padding,或改用 layer-list 堆疊多組 shape,各自只畫單邊:

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

    <item android:left="1dp">
        <shape android:shape="rectangle">
            <solid android:color="#ebebeb" />
        </shape>
    </item>

    <item
        android:left="1dp"
        android:right="1dp"
        android:top="1dp">
        <shape android:shape="rectangle">
            <solid android:color="#ebebeb" />
        </shape>
    </item>

</layer-list>

第二步:在版面中引用

<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_marginLeft="2dp"
    android:layout_marginRight="2dp"
    android:background="@drawable/shape_textview_cart"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/cart_image"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_marginRight="1dp"
        android:src="@drawable/qzone" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    </LinearLayout>

</LinearLayout>

幾個實務提醒

shape 方案的好處是可調、可 reuse、不受螢幕密度影響,邊框永遠保持 1dp 的視覺粗細;缺點是無法做出單邊粗細不同的效果,那種情況得走 layer-list 或 9-patch。

另外,若版面會大量重複使用(例如列表項),建議把邊框與圓角、內距一起定義在同一個 drawable 中,並透過樣式統一管理,避免每個版面各寫一份。

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