編輯:關於 Android 開發
原生 Button 的外觀實在樸素,專案裡幾乎一定會碰到「圓角、換底色、加描邊」這類需求。與其請設計師切一張九宮格圖,不如直接用 shape 這張可以描述出來的背景:改幾個屬性就能換色、換圓角半徑、換邊框樣式,體積也比圖片小得多。
先看成品:
在 drawable 目錄上按右鍵 → New → Drawable resource file,檔名取 buttonstyle。這裡有個容易踩到的小細節:Android Studio 產生的預設根節點是 selector,要手動改成 shape,否則後面的 solid、corners 都不會生效。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#4ec5ff" />
<padding
android:bottom="12dp"
android:left="12dp"
android:right="12dp"
android:top="12dp" />
<corners android:radius="10dp" />
<stroke
android:width="2dp"
android:color="#ffffff"
android:dashGap="270dp" />
</shape>
這段描述的其實很直白:底色填 #4ec5ff,四個角各切 10dp 圓角,再畫一圈 2dp 的白色描邊,內距統一 12dp。
如果同一個 App 裡有多顆長相類似的按鈕,把重複屬性收進 styles.xml 會省下不少力氣,之後只要引用樣式就好。
<style name="rectangle">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textSize">15sp</item>
<item name="android:textColor">#ffffff</item>
<item name="android:background">@drawable/buttonstyle</item>
</style>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.ly.blogtest.MainActivity">
<Button
android:id="@+id/button"
style="@style/rectangle"
android:text="@string/btn1" />
</RelativeLayout>
一行 style="@style/rectangle" 就把背景、字色、內距全部帶進來了,後續要換主題色只需改 shape 裡的 solid。
android:shape 決定這張背景長什麼樣子,有四個可選值:
下面這份模板把常用子標籤都列出來了,實作時挑需要的留著就好:
<shape>
<!-- 實心填充 -->
<solid android:color="#ff9d77"/>
<!-- 漸層 -->
<gradient
android:startColor="#ff8c00"
android:endColor="#FFFFFF"
android:angle="270" />
<!-- 描邊 -->
<stroke
android:width="2dp"
android:color="#dcdcdc" />
<!-- 圓角 -->
<corners
android:radius="2dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
#ff9d77。漸層可分為線性、放射與掃描三種,是做質感按鈕很好用的一招。
android:gradientRadius。radial 類型使用。LevelListDrawable 中使用。只對 rectangle 有效。四個角可以各自指定半徑,也可以只用 radius 統一設定;若把半徑開到 200dp 這類誇張數值,就會變成弧形邊。
把這幾個標籤組合起來,幾乎能應付日常九成的按鈕視覺需求,而且完全不用切圖。
Android 自定義相機界面實作:圓形拍照鍵與預覽佈局
Android 自定義相機界面實作 想製作類似原生相機的頁面,可以從佈局與自定義背景開始。本文以「圓形拍照鍵」作為切入點,說明如何利用 drawable 資源堆疊出層次感
Activity 啟動模式之 SingleTop:複用棧頂實例
規則很簡單 當 Activity 的啟動模式指定為 singleTop,系統在啟動時會先檢查返回棧的棧頂是否已經是該 Activity。如果是,就直接複用它,不再創建新實
Android 開發(2):事件處理、Toast、AlertDialog 與 Material 組件實作
前言 上一篇用 LinearLayout 加基礎組件做了一個體育積分認證系統的界面。本篇往下走一步:熟悉 Button、RadioButton、EditText 的行為,
自定義 Android 組件:用組合方式打造可切換明文的密碼輸入框
兩條自定義控件的路,選組合這條比較省力 Android 裡所有控件都繼承自 android.view.View,而 android.view.ViewGroup 是 Vi