編輯:關於 Android 程式設計
整棵 View 樹的繪圖流程由 ViewRoot 的 performTraversals() 發起,它做的事可以概括成三段判斷:是否需要重新計算大小(measure)、是否需要重新安放位置(layout)、是否需要重繪(draw)。
而 invalidate() 與 requestLayout() 則是觸發這條流程的鑰匙:
(流程圖來源:Android 開源專案源碼解析——View 繪製流程)
一個 MeasureSpec 由 size 與 mode 組成,並被壓進同一個 int 裡以減少物件配置。三種模式:
public static class MeasureSpec {
private static final int MODE_SHIFT = 30;
// int 為 32 位,最高 2 位存 mode,其餘 30 位存 size
private static final int MODE_MASK = 0x3 << MODE_SHIFT;
public static final int UNSPECIFIED = 0 << MODE_SHIFT;
public static final int EXACTLY = 1 << MODE_SHIFT;
public static final int AT_MOST = 2 << MODE_SHIFT;
/** 把 size 與 mode 打包成一個 int */
public static int makeMeasureSpec(int size, int mode) {
return size + mode;
}
/** 取出 mode */
public static int getMode(int measureSpec) {
return (measureSpec & MODE_MASK);
}
/** 取出 size */
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
}
LayoutParams 是 ViewGroup 的內部類,每種 ViewGroup 都有自己的子類,例如 RelativeLayout 對應 RelativeLayout.LayoutParams。getLayoutParams() 拿到的是其父容器類型的 LayoutParams,因此強轉前必須確定實際型別,否則會 ClassCastException。自定義的 margin 等屬性,也應該定義在自己的 LayoutParams 裡。
自定義 View 的邏輯幾乎都在 onDraw,onLayout 通常不用動,onMeasure 要自己處理測量。下面這個範例沒有實際功能,唯一目的是演示 onMeasure 與 onDraw 怎麼寫:
public class CustomView extends View {
private Paint paint = null;
private Rect rect = null;
private int bgColor = Color.parseColor("#673AB7"); // 實務上應抽成自定義屬性
private int minContentWidth = 50; // 最小內容寬度,不含 padding
private int minContentHeight = 50; // 最小內容高度,不含 padding
public CustomView(Context context) { this(context, null); }
public CustomView(Context context, AttributeSet attrs) { this(context, attrs, 0); }
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setDither(true);
paint.setColor(bgColor);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int width;
int height;
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else {
width = getPaddingLeft() + getPaddingRight() + minContentWidth;
if (widthMode == MeasureSpec.AT_MOST) {
width = Math.min(width, widthSize);
}
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize; // 注意:範例原文誤寫成 widthSize
} else {
height = getPaddingTop() + getPaddingBottom() + minContentHeight;
if (heightMode == MeasureSpec.AT_MOST) {
height = Math.min(height, heightSize);
}
}
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
rect = new Rect(getPaddingLeft(), getPaddingTop(),
getMeasuredWidth() - getPaddingRight(),
getMeasuredHeight() - getPaddingBottom());
canvas.drawRect(rect, paint);
}
}
實務上這段 onMeasure 可以直接用系統提供的 resolveSize() 或 getDefaultSize() 取代,自己手寫一遍是為了釐清思路。
public class CustomViewGroup extends ViewGroup {
public CustomViewGroup(Context context) { this(context, null); }
public CustomViewGroup(Context context, AttributeSet attrs) { this(context, attrs, 0); }
public CustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
MyLayoutParams lp = (MyLayoutParams) child.getLayoutParams();
child.layout(lp.x, lp.y,
lp.x + child.getMeasuredWidth(),
lp.y + child.getMeasuredHeight());
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = 0;
int height = getPaddingTop();
final int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
measureChild(child, widthMeasureSpec, heightMeasureSpec); // 必須呼叫
MyLayoutParams lp = (MyLayoutParams) child.getLayoutParams();
width = Math.max(width,
child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
lp.x = getPaddingLeft() + lp.leftMargin;
lp.y = height + lp.topMargin;
height = height + lp.topMargin + child.getMeasuredHeight() + lp.bottomMargin;
}
width = width + getPaddingLeft() + getPaddingRight();
height = height + getPaddingBottom();
setMeasuredDimension(
resolveSize(width, widthMeasureSpec),
resolveSize(height, heightMeasureSpec));
}
// 必須覆寫這三個方法,否則 XML 中的自定義屬性會失效
@Override
public MyLayoutParams generateLayoutParams(AttributeSet attrs) {
return new MyLayoutParams(getContext(), attrs);
}
@Override
protected MyLayoutParams generateDefaultLayoutParams() {
return new MyLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
@Override
protected MyLayoutParams generateLayoutParams(LayoutParams p) {
return new MyLayoutParams(p.width, p.height);
}
/** 繼承 MarginLayoutParams 才能使用 margin 屬性 */
public static class MyLayoutParams extends MarginLayoutParams {
public int x; // 左邊
public int y; // 上邊
public MyLayoutParams(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyLayoutParams(int w, int h) {
super(w, h);
}
}
}
Android 自學路線圖
Android 以 Linux 為基礎,主要使用 Java 開發。雖然涉及介面、資料、網路、硬體與系統整合等面向,但入門並不複雜。只要按部就班掌握每個小主題,就能逐步做出
TabLayout 自定義滑塊背景:SliderLayout 完整解析
TabLayout 是 Material Design 中的一個控件,能和 ViewPager 搭配出聯動效果。但默認的下劃線指示器並不能滿足所有設計稿——有時候我們需要
Android Studio 配置大全:從護眼配色到常用插件設置
用 Android Studio 開發 App,從一開始的不適應,到慢慢習慣,再到現在真心喜歡上它,中間頗有點曲折。這篇文章把自己在 Android Studio 上的配
Android 自定義控件:View 體系與滑動機制知識全景
寫自定義控件之前,先把地基打牢:View 到底是什麼、位置參數怎麼算、觸摸事件如何流轉、滑動有哪幾種實現方式。這一整套知識貫通之後,自定義控件就不再靠猜。 一、View