Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 實現圓角邊框:shape + corners 標籤用法詳解

編輯:Android 開發實例

本文說明如何用純 XML 的方式為控制項加上圓角背景,不必準備圖片素材。

做法是在 drawable-mdpi 目錄下定義一個 XML 檔,例如 corners_bg.xml:

 <?xml version="1.0" encoding="utf-8"?>
 <shape xmlns:android="https://schemas.android.com/apk/res/android">
   <solid android:color="#000000" />
   <corners
     android:topLeftRadius="10dp"
     android:topRightRadius="10dp"
     android:bottomRightRadius="10dp"
     android:bottomLeftRadius="10dp"/>
 </shape>

solid 決定填充色,這裡為了簡便直接用黑色。corners 則用來描述圓角。

這裡有個容易搞錯的地方值得特別提醒:屬性名稱與實際角落的對應並不直覺——bottomRightRadius 對應的是左下角,bottomLeftRadius 對應的才是右下角。寫的時候不妨對照預覽確認一下。

如果四個角半徑相同,可以簡化成一行:

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

引用時把它當成一般的 drawable 資源即可:

android:background="@drawable/corners_bg"

套用範例:main.xml

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:background="#FFFFFF">

   <RelativeLayout
     android:id="@+id/login_div"
     android:layout_width="fill_parent"
     android:layout_height="150dip"
     android:padding="15dip"
     android:layout_margin="15dip"
     android:background="@drawable/corners_bg">
   </RelativeLayout>
 </LinearLayout> 

運行結果:

延伸一下:shape 標籤的能力遠不止圓角與填色。搭配 stroke 可以畫出邊框(android:width 設粗細、android:color 設顏色),搭配 gradient 可以做漸層,padding 則能設定內距。把 solid 換成 stroke,就得到一個「只有圓角框線、內部透明」的按鈕樣式,這是介面上很常用的效果。此外若要指定不同解析度使用不同檔案,記得在 drawable-mdpi/drawable-xhdpi 等各資料夾分別放置。希望本文對大家的 Android 開發有所幫助。

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