編輯:關於 Android 程式設計
在 Android 開發過程中,系統內建的元件與屬性未必能滿足所有需求。遇到特殊情境時,我們就需要自己動手做一個自訂 View 與專屬屬性。
View 類別或其子類別。onDraw()
View 中的 onDraw() 是個空函式,也就是說具體的視圖都必須覆寫它來完成自己的繪製。ViewGroup 則不需要實作它,因為作為容器它「沒有內容」;但必須實作 dispatchDraw(),告訴子 View 該怎麼畫自己。
onLayout()
主要供 ViewGroup 型別排版子視圖使用,在 View 中它是空函式。
onMeasure()
用於計算視圖大小(長與寬),並透過 setMeasuredDimension(width, height) 保存計算結果。
onTouchEvent()
定義觸控事件以響應用戶操作。
還有一些較少用到但值得知道的方法:
onKeyDown / onKeyUp:按鍵按下與放開。onTrackballEvent:軌跡球事件。onSizeChanged():元件尺寸改變時。onFinishInflate():從 XML 載入並建立完界面之後的回呼。onWindowFocusChanged(boolean):元件取得或失去焦點時。onAttachedToWindow():元件被放入某個視窗時。onDetachedFromWindow():元件被從視窗分離時。onWindowVisibilityChanged(int):所屬視窗的可見性改變時。LayoutInflater 與 addView() 載入自訂元件的版面形成界面,不需要 onDraw()。onDraw() 繪製出元件界面。版面檔:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.demo.myView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Text="@string/hello_world" />
</RelativeLayout>
取得屬性值:
public myView(Context context, AttributeSet attrs) {
super(context, attrs);
int textId = attrs.getAttributeResourceValue(null, "Text", 0);
String text = context.getResources().getText(textId).toString();
}
這種寫法簡單,缺點是沒有型別檢查、也無法有完整的提示支援,只適合臨時或私有屬性。
在 res/values/ 下新增 attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="myView">
<attr name="text" format="string" />
<attr name="textColor" format="color" />
</declare-styleable>
</resources>
format 可以使用的型別相當豐富:
reference:參考某一資源 IDcolor:顏色值boolean:布林值dimension:尺寸值float:浮點值integer:整型值string:字串fraction:百分比enum:列舉值,例如 <enum name="horizontal" value="0" />flag:位元 OR 運算組合| 串接,例如 color|reference加到版面檔時要先宣告命名空間:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:myview="https://schemas.android.com/apk/res-auto">
<com.example.demo.myView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
myview:text="test"
myview:textColor="#ff0000" />
</RelativeLayout>
命名空間的規則是:xmlns:前綴="https://schemas.android.com/apk/包名",也可以直接用 https://schemas.android.com/apk/res-auto 讓工具自動處理。使用時寫「前綴:屬性名」即可。
在建構子中透過 TypedArray 取得:
public myView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.myView);
String text = a.getString(R.styleable.myView_text);
int textColor = a.getColor(R.styleable.myView_textColor, Color.WHITE);
a.recycle();
}
或者用遍歷的方式處理:
public myView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.myView);
int n = a.getIndexCount();
for (int i = 0; i < n; i++) {
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.myView_text:
break;
case R.styleable.myView_textColor:
break;
}
}
a.recycle();
}

要做這個效果,大致需要三個部分:在 res/values/ 下建立 attrs.xml 宣告屬性、一個繼承 View 並覆寫部分函式的自訂類別、一個承載它的容器版面。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="myView">
<attr name="TextColor" format="color" />
</declare-styleable>
</resources>
在建構子中取得屬性,並覆寫 onDraw() 與 onTouchEvent() 完成繪製與事件響應。
public class myView extends View {
private final Paint p = new Paint();
public float currentX = 50;
public float currentY = 50;
public int textColor;
public myView(Context context, AttributeSet attrs) {
super(context, attrs);
// 只有一個屬性時不必遍歷,直接取出 color 值
// 把屬性放進資源檔,方便設定與複用
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.myView);
textColor = array.getColor(R.styleable.myView_TextColor, Color.BLACK);
array.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 畫一個藍色的圓
p.setColor(Color.BLUE);
canvas.drawCircle(currentX, currentY, 30, p);
// 使用資源檔設定的文字顏色
p.setColor(textColor);
canvas.drawText("BY finch", currentX - 30, currentY + 50, p);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
currentX = event.getX();
currentY = event.getY();
invalidate(); // 觸發重新繪製
return true;
}
}

原理很單純:不斷更新目前座標並呼叫 invalidate() 重新繪製。要注意的是,使用 TypedArray 之後一定要呼叫 recycle(),否則會影響下一次取得屬性。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
xmlns:myview="https://schemas.android.com/apk/res-auto"
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="finch.scu.cn.myview.MainActivity">
<finch.scu.cn.myview.myView
android:layout_width="match_parent"
android:layout_height="match_parent"
myview:TextColor="#ff0000" />
</RelativeLayout>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
具體怎麼做,取決於具體需求。舉例來說,如果要做「側滑刪除」的 ListView,就可以繼承 ListView、監聽側滑事件、在滑動時顯示刪除按鈕來完成功能。
幾個通用原則值得記住:屬性盡量用 attrs.xml 正式宣告以获得型別支援;onDraw() 裡不要建立物件,也避免配置記憶體;invalidate() 會觸發重繪,在 onDraw() 中呼叫它會造成無限迴圈。
在 Ubuntu 上搭建 Android 開發環境(Android Studio)實錄
假期沒事,裝了最新的 Ubuntu 16.04,順手把 Android 開發環境也搬過來體驗一下。整個過程不算太順,踩了幾個坑,記錄下來給要走同一條路的人參考。 一、下
Android greenDAO 使用教學與查詢技巧
greenDAO 的定位 greenDAO 是 Android 上的 ORM 工具,能將 Java 物件對應到 SQLite 資料表,減少手寫 SQL 與重複樣板程式碼。
Android EventBus 入門:事件傳遞機制與 ThreadMode 解析
EventBus 的運作邏輯一句話就能講完:把要傳遞的 event(本質上就是任意自訂的 Object)丟進 EventBus 這個公共元件暫存,再由它轉發給訂閱者;訂閱
Android 架構模式詳解:MVC、MVP 與 MVVM 的區別與實踐
MVC、MVP、MVVM,這三個名字相信大家都耳熟能詳。作為 Android 開發中最常被提及的架構模式,它們的應用範圍極廣。但對不少新手來說,光是分清三者就已頗具挑戰,