編輯: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"
<?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 開發有所幫助。
Android MediaPlayer 使用指南:播放控制、進度條與快轉倒轉
要在 App 裡播放音訊或影片,Android 提供了多種途徑,其中最直接的就是 MediaPlayer。它屬於系統內建的媒體播放服務,透過這個類別,你能以幾行程式碼完成
Android 開發自學筆記(五):用程式碼把版面串成真正的功能
好看的骨架已經有了,接下來要讓它真正動起來。只有外表、沒有內涵的花拳繡腿可不行。 從前面幾篇,我們已經能把版面搭成這個樣子: 相關文章:Android 自學開發第四篇之
Android Notification 用法總整理:四種建立方式與版本演進
手機來了簡訊而你沒點開,狀態欄上方會留一個小圖示提醒你——這就是 Notification。想在自己的應用裡做類似的事,就得把 Notification 這套 API 摸
Android Spinner 載入動畫:按鈕觸發與顯示控制
Spinner 是 Android 中常見的等待提示元件。當使用者觸發某個操作,但系統需要一點時間處理時,可以用轉圈動畫告知目前仍在進行中。 基本設定 在版面配置中加入