編輯:關於 Android 程式設計
做 Android 開發遲早會遇到「現有控制項不夠用」的時刻。這時候就得自己寫 View。本文把自定義控件的完整流程拆成六個步驟,並把背後的原理講清楚。
Android 的視圖結構採用組合模式:View 是所有圖形的基類,ViewGroup 則是「容器型」的 View,負責裝載與管理子 View。
View 定義了三個核心操作:measure()、layout()、draw(),各自內部又對應 onMeasure()、onLayout()、onDraw() 三個可覆寫的鉤子。
負責計算視圖的寬與高,在 View 中被宣告為 final,子類不能改。它內部會呼叫 onMeasure(),最終尺寸在這裡確定,並透過 setMeasuredDimension(width, height) 保存結果。所以自定義 View 想控制自己的大小,覆寫 onMeasure() 才是正解。
同樣是 final 方法,內部有兩個關鍵動作:
setFrame(l, t, r, b):把子視圖相對於父容器的四邊座標存起來;onLayout():在 View 中是空實作,只有 ViewGroup 類型的容器才需要覆寫它來排列子元素。draw 會依序完成一連串固定步驟:
onDraw() 繪製視圖自身內容——在 View 中它是空函數,TextView 這類控件正是在這裡實作文字繪製;ViewGroup 因為「本身沒有內容」,通常不需要實作;dispatchDraw() 繪製子視圖,這是專門留給容器類的;結論:自定義 View 最少要覆寫 onMeasure() 與 onDraw()。
透過 AttributeSet 查 XML 中的屬性名稱,再找到對應的資源 ID 取值。下面做一個「圖片 + 文字」的簡單控件:
public class MyView extends View {
private String mtext;
private int msrc;
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
int textId = attrs.getAttributeResourceValue(null, "Text", 0);
int srcId = attrs.getAttributeResourceValue(null, "Src", 0);
mtext = context.getResources().getText(textId).toString();
msrc = srcId;
}
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.RED);
InputStream is = getResources().openRawResource(msrc);
Bitmap mBitmap = BitmapFactory.decodeStream(is);
int bh = mBitmap.getHeight();
int bw = mBitmap.getWidth();
canvas.drawBitmap(mBitmap, 0, 0, paint);
canvas.drawText(mtext, bw / 2, 30, paint);
}
}
對應布局檔直接在標籤上寫屬性即可:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.myimageview2.MyView
android:id="@+id/myView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
src="@drawable/xh"
text="@string/hello_world" />
</LinearLayout>
這種寫法與 Android 系統屬性完全一致,是更推薦的方式。以下實作一個「ImageView + TextView」的組合控件,文字位置可在布局檔中指定:
public class MyImageView extends LinearLayout {
public MyImageView(Context context) {
super(context);
}
public MyImageView(Context context, AttributeSet attrs) {
super(context, attrs);
int resourceId = -1;
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyImageView);
ImageView iv = new ImageView(context);
TextView tv = new TextView(context);
int N = typedArray.getIndexCount();
for (int i = 0; i < N; i++) {
int attr = typedArray.getIndex(i);
switch (attr) {
case R.styleable.MyImageView_Oriental:
resourceId = typedArray.getInt(R.styleable.MyImageView_Oriental, 0);
setOrientation(resourceId == 1 ? HORIZONTAL : VERTICAL);
break;
case R.styleable.MyImageView_Text:
resourceId = typedArray.getResourceId(R.styleable.MyImageView_Text, 0);
tv.setText(resourceId > 0
? typedArray.getResources().getText(resourceId)
: typedArray.getString(R.styleable.MyImageView_Text));
break;
case R.styleable.MyImageView_Src:
resourceId = typedArray.getResourceId(R.styleable.MyImageView_Src, 0);
iv.setImageResource(resourceId > 0 ? resourceId : R.drawable.ic_launcher);
break;
}
}
addView(iv);
addView(tv);
typedArray.recycle();
}
}
在 values 目錄下的 attrs.xml 中聲明:
<resources>
<declare-styleable name="MyImageView">
<attr name="Oriental">
<enum name="Horizontal" value="1" />
<enum name="Vertical" value="0" />
</attr>
<attr name="Text" format="string|reference" />
<attr name="Src" format="reference" />
</declare-styleable>
</resources>
使用時先宣告命名空間(包名需與 manifest 中一致),之後就能像系統屬性一樣寫:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:uview="https://schemas.android.com/apk/res/com.example.myimageview2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.myimageview2.MyImageView
android:id="@+id/myImageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
uview:Oriental="Vertical"
uview:Src="@drawable/tw"
uview:Text="這是一個圖片說明" />
</LinearLayout>
把自定義 View 的生命週期回調整理成一份速查表,開發時對照著看會快很多:
onFinishInflate():XML 中的該元件已經被載入並建構完成之後呼叫。onMeasure():量測自身與子元件的大小。onLayout():需要為子元件分配位置與大小時。onSizeChanged():自身尺寸發生變化時。onDraw():即將繪製內容時。onKeyDown() / onKeyUp():按鍵按下與放開。onTrackballEvent():軌跡球事件。onTouchEvent():觸控事件。onWindowFocusChanged(boolean):視窗焦點取得或失去。onAttachedToWindow():元件被放入某個視窗時。onDetachedFromWindow():元件從視窗分離時。onWindowVisibilityChanged(int):所屬視窗可見性改變時。掌握這幾個時機,自定義 View 的行為就能完全按你的設想去運作。
RecyclerView DiffUtil 使用詳解:差異計算與局部刷新
為什麼需要 DiffUtil?在 RecyclerView 中,若資料集合發生變化,最簡單的做法是呼叫 notifyDataSetChanged。但這種方式會刷新整個列表
Fragment A 內嵌 Fragment B,B 內再嵌 C:兩個報錯的處理方式
問題情境 專案結構是 Activity A 中掛 Fragment B,Fragment B 內部再掛 Fragment C: 問題一:切換主選單時出現「Fragmen
刷機精靈 adb 怎麼刷機?常用指令速查
用過刷機精靈新版的人,大概都看過那個 adb 命令工具。多數人對指令行本來就陌生,非必要時並不建議走這條路,但遇到工具圖形介面搞不定的狀況,adb 往往是最後手段。以下把
Android 三種菜單機制深度解析:OptionMenu、ActionMode 與 PopupMenu
以下說明皆以 Android 3.0(API 11)為基準。本文將依序介紹三種基本菜單:PartA 操作欄(選項菜單 OptionMenu)、PartB 上下文操作模式(