編輯:關於 Android 程式設計
Android 的視圖控制項大致分為兩類:ViewGroup 與 View。ViewGroup 作為父容器,包含並管理子 View;兩者共同構成一棵「控制項樹」,每個 ViewGroup 與 View 就是樹上的節點。查找控制項時以樹的深度遍歷,而上層控制項負責下層子控制項的測量、配置與事件傳遞。
Android 控制項樹:

Android UI 介面架構:

MeasureSpec.getMode() 與 MeasureSpec.getSize() 取得。layout_width/layout_height 指定具體數值或 match_parent。此時上層已經明確告訴你該有多大,直接採用即可。wrap_content。上層給了一個上限,你要在這個範圍內決定自己的大小。要支援其他模式就必須自行覆寫 onMeasure(),模板如下:
package com.example.demoapp.views;
import android.content.Context;
import android.view.View;
public class MeasuredView extends View {
public MeasuredView(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 呼叫父類的 onMeasure()
super.onMeasure(measureWidth(widthMeasureSpec),
measureHeight(heightMeasureSpec));
// 或者直接呼叫 setMeasuredDimension(),因為父類 onMeasure() 最終也是呼叫它
// setMeasuredDimension(measureWidth(widthMeasureSpec),
// measureHeight(heightMeasureSpec));
}
/** 測量 View 的寬度 */
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = 200; // 自訂的預設寬度
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
/** 測量 View 的高度 */
private int measureHeight(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = 200; // 自訂的預設高度
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
}
這段程式示範了一個關鍵觀念:處理 AT_MOST 時,一定要用 Math.min() 把自己的期望值與上層給的上限取小,否則自訂 View 會撐破父容器。
View.onDraw(Canvas canvas) 的參數就是一個 Canvas。Canvas canvas = new Canvas(bitmap)。傳入 Bitmap 的過程稱為「畫布的裝載」,該 Bitmap 承載了所有繪製在 Canvas 上的像素;此後呼叫 canvas.drawBitmap() 等方法,實際作用的對象就是這個 Bitmap。measure() 取得各自的測量結果。layout() 把它們放到正確位置。onLayout() 來控制子 View 的擺放。wrap_content,必須覆寫 onMeasure()。一般情況下 ViewGroup 本身不需要繪製內容,但它會透過 dispatchDraw() 來繪製它的子 View。
onDraw() 繪製顯示內容;若需支援 wrap_content,還必須覆寫 onMeasure()。onFinishInflate():從 XML 載入完控制項後回呼。onSizeChanged():控制項尺寸改變時回呼。onMeasure():進行測量。onLayout():決定顯示位置。onTouchEvent():處理觸控事件。onDraw(),對原生控制項做擴充。addView() 加入具備特定功能的小控制項,組合成複合控制項。onDraw() 與 onMeasure() 實作繪製邏輯,覆寫 onTouchEvent() 實作互動邏輯,做出全新的控制項。在 res/values/ 下建立 attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="customAttr">
<attr name="title" format="string" />
<attr name="fontSize" format="dimension" />
<attr name="fontColor" format="color" />
<attr name="background" format="reference|color" />
<attr name="fontStyle" format="enum" />
<attr name="shadeSupport" format="boolean" />
</declare-styleable>
</resources>
再以 TypedArray 取值(取完務必 recycle):
package com.jy.myrecyclerview.test;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import com.jy.myrecyclerview.R;
public class TestCustomAttrs extends View {
private Context mContext;
private AttributeSet mAttrs;
private String mTitle;
private float mFontSize;
private int mFontColor;
private int mBackground;
private int mFontStyle;
private boolean mShadeSupport;
public TestCustomAttrs(Context context) {
super(context);
this.mContext = context;
}
public TestCustomAttrs(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
this.mAttrs = attrs;
}
public TestCustomAttrs(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext = context;
this.mAttrs = attrs;
}
private void getCustomAttrs() {
TypedArray ta = mContext.obtainStyledAttributes(mAttrs, R.styleable.customAttr);
mTitle = ta.getString(R.styleable.customAttr_title);
mFontSize = ta.getDimension(R.styleable.customAttr_fontSize, 10);
mFontColor = ta.getColor(R.styleable.customAttr_fontColor, 0);
mBackground = ta.getColor(R.styleable.customAttr_background, 0);
mFontStyle = ta.getInt(R.styleable.customAttr_fontStyle, 0);
mShadeSupport = ta.getBoolean(R.styleable.customAttr_shadeSupport, false);
ta.recycle();
}
}
此外,定義回呼介面能讓自訂控制項對外更靈活;而在版面中引用時,需要宣告命名空間 xmlns:custom="https://schemas.android.com/apk/res-auto":
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:custom="https://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.jy.myrecyclerview.test.TestCustomAttrs
android:id="@+id/id_recyclerview"
android:divider="#ffff0000"
android:dividerHeight="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
custom:title="title"
custom:fontSize="12sp"
custom:fontColor="@color/colorPrimary"
custom:background="@color/colorPrimary"
custom:shadeSupport="false" />
</RelativeLayout>
onMeasure():對子 View 進行測量。onLayout():決定子 View 的位置。onTouchEvent():處理觸控互動。把整條鏈串起來看:MeasureSpec 由父容器傳下來 → onMeasure 決定自己的尺寸 → onLayout 決定子 View 的位置 → onDraw/dispatchDraw 完成繪製。自訂控制項時遇到的多數問題,都能回到這條流程上定位是哪一步出了錯。
Android 6.0 執行期權限(Runtime Permission)機制源碼剖析
Android 升級到 6.0 之後,為了改善長久以來為人詬病的安全形象,在原本「安裝時一次授予」的基礎上,對其中一部分危險權限改採動態授予的方式,類似各家手機安全助手提
Android 事件分發源碼解析(上):View 層的完整執行鏈路
一、前言 讀完《Android 開發藝術探索》第三章,我對事件分發機制有了整體輪廓。網路上討論這個主題的文章很多,自己也翻了一些,但始終覺得不如自己跟一遍源碼來得踏實。所
微信 Android 熱補丁技術的實踐與演進之路
繼插件化之後,熱補丁技術在 2015 年迎來爆發,如今已成為 Android 開發領域極受矚目的一門技術。其中比較知名的有淘寶的 Dexposed、支付寶的 AndFix
以 AccessibilityService 為基礎,拆解 Android 自動化操作的三個環節
本文以「自動處理聊天中的紅包消息」為案例,說明 Android 無障礙服務(AccessibilityService)在自動化場景下的完整用法:監聽畫面變化、定位目標控制