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

Android UI:用 shape 自定義控件形狀

在 Android 界面開發中,想讓 EditText、按鈕等控件擁有圓角、描邊或自定義背景,最簡單的方式就是借助 shape 這張「形狀畫布」。下面以一個帶圓角、內邊距與描邊的樣例說明做法。

第一步:定義 shape.xml

先在 res/drawable 目錄下新建 shape.xml,內容如下:

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

    <solid android:color="#ffffffff" />

    <corners android:radius="10dp" />

    <padding
        android:bottom="10dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />

    <stroke
        android:width="2dp"
        android:color="#ff00bbe8" />

</shape>

其中 solid 決定填充色,corners 設定圓角半徑,padding 控制內邊距,stroke 則負責描邊的粗細與顏色。

第二步:在布局中引用

需要用到這個形狀時,把它作為 android:background 指定給控件即可:

<EditText
    android:id="@+id/mText"
    android:layout_width="fill_parent"
    android:layout_height="100px"
    android:background="@drawable/shape"
    android:textColor="#aa000000"
    android:textSize="20dp"
    android:gravity="top"
    android:layout_margin="3dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" />

如此一來,這個 EditText 便擁有了白色底、圓角與淺藍描邊的外觀,無需任何切圖就能得到精致的界面效果。

Copyright © Linux教程網 All Rights Reserved