編輯:關於 Android 程式設計
想要實現產品經理筆下那些「設計稿裡有、系統裡沒有」的效果,自定義 View 是必備技能。動手之前,先把 View 與 ViewGroup 的分工搞清楚。
下面的代碼構建了一個包含兩個 Button 和一個 TextView 的容器,但由於 onLayout 是空實現,子控件不會顯示:
public class MyViewGroup extends ViewGroup {
public MyViewGroup(Context context) {
super(context);
Button button1 = new Button(context);
button1.setText("button1");
Button button2 = new Button(context);
button2.setText("button2");
TextView textView = new TextView(context);
textView.setText("textView");
addView(button1);
addView(button2);
addView(textView);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// 空實現,子控件不會顯示
}
}
View 的 layout(int left, int top, int right, int bottom) 方法決定了它最終顯示在哪裡。我們在 onLayout 中遍歷所有子 View 並調用 layout:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount = getChildCount();
int left = 0;
int top = 10;
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
child.layout(left, top, left + 60, top + 60);
top += 70;
}
}
每個子 View 的 layout 又會觸發自身的 onLayout,於是形成一個遞歸的佈局調用鏈。這正是 Android 佈局系統的基本運作方式。
onMeasure 決定了容器自身以及每個子 View 的測量尺寸:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int childCount = getChildCount();
// 設置該 ViewGroup 自身的大小
int specSizeWidth = MeasureSpec.getSize(widthMeasureSpec);
int specSizeHeight = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(specSizeWidth, specSizeHeight);
// 為每個子 View 指定大小
for (int i = 0; i < childCount; i++) {
View childView = getChildAt(i);
childView.measure(80, 80);
}
}
重寫 onMeasure 的好處很直接:既能控制容器自身尺寸,也能精確分配每個子 View 的寬高。
如果內容超出屏幕,就需要處理觸摸事件並調用 scrollBy:
public boolean onTouchEvent(MotionEvent ev) {
final float y = ev.getY();
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastMotionY = y;
break;
case MotionEvent.ACTION_MOVE:
int detaY = (int) (mLastMotionY - y);
mLastMotionY = y;
scrollBy(0, detaY);
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
View 提供了 scrollTo(int x, int y) 與 scrollBy(int x, int y) 兩個方法,看起來都是在移動視圖,實際含義不同:scrollTo 是滑動到「絕對坐標」,scrollBy 是滑動到「相對當前位置的偏移量」。日常滾動實現中,後者使用頻率更高。
理解這兩個方法的前提,是理解 Android 的兩套坐標:
由於布局坐標只能呈現特定區域的內容,只要移動布局坐標的原點,就能把視圖坐標中的任意位置顯示出來——這正是滾動的本質。
如果你在 ViewGroup 中重寫了 onDraw 方法,卻發現系統根本不調用它,記得在構造方法中加上:
setWillNotDraw(false);
ViewGroup 默認會跳過自身的繪製流程(因為它主要承擔佈局職責),只有顯式打開這個開關,重寫的 onDraw(Canvas canvas) 才會被執行。
自定義控件的學習路徑大致是:先理清 onMeasure(多大)、onLayout(放哪)、onDraw(畫什麼)三大職責,再逐步加入觸摸交互與滾動處理。把這條主線走通,再複雜的自定義效果都有跡可循。
自定義 View 實作動態圓形進度條
客製化 View 是 Android 開發中常見的需求。若現成元件無法符合設計,就可以透過 Canvas 與 Paint 自行繪製。圓形進度條就是一個很適合用來練習自定義
Android 安全加密系列:消息摘要 Message Digest 完全指南
系列文章索引 Android 安全加密:對稱加密 Android 安全加密:非對稱加密 Android 安全加密:消息摘要 Message Digest Android
Android WebView 基本用法:與原生代碼雙向通信實踐
一直覺得把 Web 技術和 Android 原生組件結合起來做應用有事半功倍的效果,HTML5 普及之後更是如此——對原本做 Web 開發的同學來說,這幾乎是最短的一條入
網頁如何喚起本機 APK:Android Scheme 跳轉完整解析
行動版瀏覽器打開 m.alipay.com 時,如果手機裝了支付寶就直接跳進客戶端,沒裝則導向安裝頁——這個體驗背後靠的是 URL Scheme 攔截。本文把整個機制拆開