編輯:關於 Android 程式設計
登錄框、卡片、標籤這類元素經常需要圓角。與其反覆切圖,不如用 XML 描述——Android 的 Drawable 系統提供了 shape 標籤,改起來比換圖片方便得多。
在 drawable-mdpi 目錄下新建一個 XML 文件(本例命名 corners_bg.xml):
<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 描述四個角的圓弧半徑。
有個容易搞錯的細節:在 Android 的 corners 定義中,bottomRightRadius 對應的是左下角,bottomLeftRadius 對應的是右下角,命名與視覺位置是交叉的。如果四個角半徑相同,不必寫四遍,直接用簡化寫法即可:
<corners android:radius="5dp" />
引用時寫 @drawable/corners_bg,不需要帶後綴:
<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> 畫邊框,可設置 color 與 width。做「白底灰框圓角按鈕」時,它與 corners 的組合是標準套路。
<gradient> 實現漸變填充,配合 startColor、endColor 與 angle 就能做出簡單的漸變背景。
<padding> 在 Drawable 層面定義內邊距,與 View 的 padding 屬性效果重疊但作用範圍不同。
需要注意的是,早期版本中 shape 的圓角不會自動裁剪子內容。如果要在圓角容器裡放圖片並讓圖片也跟著圓角,得靠 android:clipToOutline(API 21 及以上)或自定義 ImageView 實現。
Android 動畫系統之視圖動畫(View Animation)入門與實戰
視圖動畫的適用場景與局限 視圖動畫(又稱補間動畫)是最早的一套動畫方案,使用簡單但有明確邊界: 只能為 View 添加動畫。若想讓非 View 對象动起来,只能自己實現
Android 自定義趨勢圖實作分享
先前專案有個需求:依據一週的天氣溫度畫出趨勢圖。這張圖不走傳統 XY 座標軸的路子,就是一條純粹的折線走勢。查了幾篇相關文章後大致有了方向,最終效果如下圖,最下方的點線圖
Android TabLayout 結合 ViewPager 實現分頁切換教學
在 Android 中,TabLayout 與 ViewPager 是非常常見的組合,適合用來建立頂部頁籤與可滑動頁面的結構。只要把兩者綁定在一起,就能讓使用者透過點擊頁
Android Activity 生命週期完整解析
Android Activity 生命週期 Activity 是 Android 應用中的單一畫面。每個 Activity 都有完整的生命週期,系統會依據使用者操作、記憶