Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

《Android 群英傳》知識點回顧(三):控件架構、自定義 View 與事件攔截

編輯:關於 Android 程式設計

第三章是整本書裡最「值得反覆看」的一章,因為它把 UI 的底層規則講清楚了:View 怎麼量、怎麼畫、怎麼擺放,以及觸控事件到底在誰手上流轉。以下依序回顧,並附上六個可跑的經典範例。

本章目錄

3.1 Android 控件架構 3.2 View 的測量 3.3 View 的繪製 3.4 ViewGroup 的測量 3.5 ViewGroup 的繪製
3.6 自定義 View(擴展現有控件/建立複合控件/重寫 View)
3.7 自定義 ViewGroup 3.8 事件攔截機制

3.1 控件架構

控件分兩大類:View(視圖控件)與 ViewGroup(包含並管理多個 View)。兩者的關係是:上層負責下層子控件的測量與繪製,並向下傳遞交互事件。

整個 UI 的骨架是這樣組起來的:

每個 Activity 都含一個 Window 物件,通常由 PhoneWindow 實作。PhoneWindow 會把一個 DecorView 設為整個應用視窗的根 View,也就是最頂層。DecorView 只有一個子元素——一個 LinearLayout,代表整個視窗,內含通知欄、標題欄、內容顯示欄三塊區域。這個 LinearLayout 底下有兩個 FrameLayout 子元素:一個負責標題欄(只有一個 TextView 顯示應用名稱),一個負責內容欄,也就是 setContentView() 載入的佈局。

3.2 View 的測量

核心類別是 MeasureSpec:一個 32 位元整數,高 2 位是測量模式,低 30 位是測量大小。三種模式:

EXACTLY:精確模式。layout_width/layout_height 指定了具體值時使用。
AT_MOST:最大值模式。屬性設為 wrap_content 時使用,尺寸不得超過父容器給的上限。
UNSPECIFIED:未指定模式。要多大就多大,一般只在自定義 View 的特殊場景才會用到。

關鍵結論:View 預設的 onMeasure() 只支援 EXACTLY。這就是為什麼自定義 View 寫 wrap_content 往往沒有效果——你必須自己重寫 onMeasure()。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

跟進父類實作會看到,最終它會呼叫 setMeasuredDimension() 把量到的寬高寫回去:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(
        getDefaultSize(getSuggestedMinimumWidth(),  widthMeasureSpec),
        getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}

所以我們只要把這兩個參數換成自己算的結果即可:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));
}

以寬度為例,標準寫法是「先取出模式與尺寸,再依模式給值」:

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;                   // wrap_content 時給一個預設值
        if (specMode == MeasureSpec.AT_MOST) {
            result = Math.min(result, specSize);   // 別超出父容器上限
        }
    }
    return result;
}

這段幾乎可以當模板直接抄。wrap_content 時拿到 200px 的預設寬,就是靠這裡決定的。

3.3 View 的繪製

量好之後,重寫 onDraw() 來畫。所有繪製行為都發生在 Canvas 上:

Canvas canvas = new Canvas(bitmap);

Canvas 就像畫板,傳進一個 Bitmap 後兩者緊密綁定,這個過程叫「裝載畫布」。該 Bitmap 用來存放所有畫在 Canvas 上的像素,因此後續任何 canvas.drawXxx() 的結果都會落在這張 Bitmap 上。

3.4 / 3.5 ViewGroup 的測量與繪製

ViewGroup 測量時會遍歷所有子 View,逐一呼叫 measure:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int childCount = getChildCount();
    for (int i = 0; i < childCount; i++) {
        getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
    }
}

量完之後,通常要重寫 onLayout() 決定每個子 View 擺在哪:

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    for (int i = 0; i < getChildCount(); i++) {
        this.getChildAt(i).layout(l, t, r, b);
    }
}

至於繪製,ViewGroup 通常不需要自己畫——除非你設了背景色,否則它的 onDraw() 根本不會被呼叫。它真正要做的是用 dispatchDraw() 把子 View 畫出來:

@Override
protected void dispatchDraw(Canvas canvas) {
    super.dispatchDraw(canvas);
}

3.6 自定義 View 的五個關鍵回調

onFinishInflate():從 XML 載入元件後回呼。
onSizeChanged():元件大小改變時回呼,第一次拿到真實尺寸通常就在這裡。
onMeasure():進行測量。
onLayout():決定顯示位置。
onTouchEvent():收到觸摸事件時回呼。

實作自定義控件的三條路:擴展現有控件、組合出複合控件、重寫 View 做出全新控件。以下六個範例分別對應這三條路。

範例一:擴展 TextView,加外框與內距

public class CustomTextView extends TextView {

    private Paint paint1, paint2;

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPaint();
    }

    private void initPaint() {
        paint1 = new Paint();
        paint1.setColor(getResources().getColor(android.R.color.holo_blue_light));
        paint1.setStyle(Paint.Style.FILL);

        paint2 = new Paint();
        paint2.setColor(Color.YELLOW);
        paint2.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), paint1);            // 外框
        canvas.drawRect(10, 10, getMeasuredWidth() - 10, getMeasuredHeight() - 10, paint2); // 內框
        canvas.save();
        canvas.translate(10, 0);   // 文字右移 10px,避開內框
        super.onDraw(canvas);      // 交回父類完成文字繪製
        canvas.restore();
    }
}

注意 canvas.save() 與 restore() 的配對:平移是暫時的,畫完必須還原,否則會污染後續繪製。

範例二:漸層掃過的閃動文字

技巧是用 LinearGradient 當作文字的 Shader,再透過 Matrix 讓漸層起點不斷平移,營造光帶掃過的錯覺。

public class FlashTextView extends TextView {

    int mViewWidth = 0;
    private Paint mPaint;
    private LinearGradient mLinearGradient;
    private Matrix matrix;
    private int mTranslate;

    public FlashTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (mViewWidth == 0) {
            mViewWidth = getMeasuredWidth();
            if (mViewWidth > 0) {
                mPaint = getPaint();
                mLinearGradient = new LinearGradient(0, 0, mViewWidth, 0,
                        new int[]{ Color.BLUE, 0xffffffff, Color.BLUE },
                        null, Shader.TileMode.CLAMP);
                mPaint.setShader(mLinearGradient);
                matrix = new Matrix();
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (matrix != null) {
            mTranslate += mViewWidth + 5;
            if (mTranslate > 2 * mViewWidth / 5) {
                mTranslate = -mViewWidth;    // 循環重置
            }
            matrix.setTranslate(mTranslate, 0);
            mLinearGradient.setLocalMatrix(matrix);
            postInvalidateDelayed(100);      // 100ms 後重繪,形成動畫
        }
    }
}

這裡有個實務重點:初始化必須放在 onSizeChanged() 而非建構子,因為建構階段還拿不到真正的寬度。

範例三:自定義 ToolBar(複合控件)

先在 values 底下新增 attrs.xml 宣告自定義屬性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TopBar">
        <!-- leftText / leftTextColor / leftBackground
             rightText / rightTextColor / rightBackground
             title / titleTextSize / titleTextColor -->
    </declare-styleable>
</resources>

接著在建構子中透過 obtainStyledAttributes() 把 XML 上的屬性讀進 TypedArray,取出後記得 recycle():

public class ToolBar extends RelativeLayout {

    private int mLeftTextColor;
    private Drawable mLeftBackground;
    private String mLeftText;
    private int mRightTextColor;
    private Drawable mRightBackgroup;
    private String mRightText;
    private float mTitleTextSize;
    private int mTitleTextColor;
    private String mTitle;

    private Button mLeftButton;
    private Button mRightButton;
    private TextView mTitleView;

    private RelativeLayout.LayoutParams mLeftParams;
    private RelativeLayout.LayoutParams mRightParams;
    private RelativeLayout.LayoutParams mTitleParams;

    public ToolBar(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TopBar);

        mLeftTextColor  = ta.getColor(R.styleable.TopBar_leftTextColor, 0);
        mLeftBackground = ta.getDrawable(R.styleable.TopBar_leftBackground);
        mLeftText       = ta.getString(R.styleable.TopBar_leftText);
        mRightTextColor = ta.getColor(R.styleable.TopBar_rightTextColor, 0);
        mRightBackgroup = ta.getDrawable(R.styleable.TopBar_rightBackground);
        mRightText      = ta.getString(R.styleable.TopBar_rightText);
        mTitleTextSize  = ta.getDimension(R.styleable.TopBar_titleTextSize, 10);
        mTitleTextColor = ta.getColor(R.styleable.TopBar_titleTextColor, 0);
        mTitle          = ta.getString(R.styleable.TopBar_title);

        ta.recycle();   // 取完務必回收,避免重複建立時出錯

        mLeftButton  = new Button(context);
        mRightButton = new Button(context);
        mTitleView   = new TextView(context);

        mLeftButton.setTextColor(mLeftTextColor);
        mLeftButton.setBackground(mLeftBackground);
        mLeftButton.setText(mLeftText);

        mRightButton.setTextColor(mRightTextColor);
        mRightButton.setBackground(mRightBackgroup);
        mRightButton.setText(mRightText);

        mTitleView.setText(mTitle);
        mTitleView.setTextColor(mTitleTextColor);
        mTitleView.setTextSize(mTitleTextSize);
        mTitleView.setGravity(Gravity.CENTER);

        // 左按鈕靠左
        mLeftParams = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        mLeftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        addView(mLeftButton, mLeftParams);

        // 右按鈕靠右
        mRightParams = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        mRightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        addView(mRightButton, mRightParams);

        // 標題居中
        mTitleParams = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        mTitleParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        addView(mTitleView, mTitleParams);
    }
}

XML 中使用時,別忘了加上 xmlns:custom="https://schemas.android.com/apk/res-auto":

<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.handsome.qunyingzhuang.chapter_3.toolbar.ToolBar
        android:layout_width="match_parent"
        android:layout_height="40dp"
        custom:leftBackground="#0000ff"
        custom:leftText="back"
        custom:leftTextColor="#00ff00"
        custom:rightBackground="#333333"
        custom:rightText="more"
        custom:rightTextColor="#ff0000"
        custom:title="我的標題"
        custom:titleTextColor="#ff0000"
        custom:titleTextSize="14sp" />
</RelativeLayout>

範例四:弧線進度圖

public class CircleProgressView extends View {

    private int mCircleXY;
    private int length;
    private float mRadius;

    private Paint mCirclePaint;
    private Paint mArcPaint;
    private Paint mTextPaint;

    private String mShowText = "Hensen_";
    private int mTextSize = 25;
    private float mSweepValue = 270;

    public CircleProgressView(Context context, AttributeSet attrs) {
        super(context, attrs);
        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        length = wm.getDefaultDisplay().getWidth();
        init();
    }

    private void init() {
        mCircleXY = length / 2;
        mRadius   = (float) (length * 0.5 / 2);

        mCirclePaint = new Paint();
        mCirclePaint.setColor(Color.BLUE);

        mArcPaint = new Paint();
        mArcPaint.setStrokeWidth(50);
        mArcPaint.setStyle(Paint.Style.STROKE);
        mArcPaint.setColor(Color.BLUE);

        mTextPaint = new Paint();
        mTextPaint.setColor(Color.WHITE);
        mTextPaint.setTextSize(mTextSize);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        RectF mArcRectF = new RectF((float) (length * 0.1), (float) (length * 0.1),
                                    (float) (length * 0.9), (float) (length * 0.9));
        canvas.drawCircle(mCircleXY, mCircleXY, mRadius, mCirclePaint);
        canvas.drawArc(mArcRectF, 270, mSweepValue, false, mArcPaint);
        canvas.drawText(mShowText, 0, mShowText.length(),
                        mCircleXY, mCircleXY + (mTextSize / 4), mTextPaint);
    }

    public void setSweepValue(float sweepValue) {
        mSweepValue = (sweepValue != 0) ? sweepValue : 25;
        invalidate();
    }
}

外部呼叫一行就能更新比例:

CircleProgressView circleProgressView = (CircleProgressView) findViewById(R.id.circle);
circleProgressView.setSweepValue(270);

範例五:音訊條形圖

public class MusicView extends View {

    private int mWidth;
    private int mRectHeight;
    private int mRectWidth;
    private int mRectCount = 20;

    private LinearGradient mLinearGradient;
    private Paint mPaint = new Paint();

    private float currentHeight;
    private int offset = 5;
    private double mRandom;

    public MusicView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth      = getWidth();
        mRectHeight = getHeight();
        mRectWidth  = (int) (mWidth * 0.6 / mRectCount);
        mLinearGradient = new LinearGradient(0, 0, mRectWidth, mRectHeight,
                Color.YELLOW, Color.BLUE, Shader.TileMode.CLAMP);
        mPaint.setShader(mLinearGradient);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i = 0; i < mRectCount; i++) {
            canvas.drawRect(
                    (float) (mWidth * 0.4 / 2 + mRectWidth * i + offset), currentHeight,
                    (float) (mWidth * 0.4 / 2 + mRectWidth * (i + 1)), mRectHeight,
                    mPaint);
        }
        mRandom = Math.random();
        currentHeight = (float) (mRectHeight * mRandom);
        postInvalidateDelayed(300);   // 每 300ms 換一次高度
    }
}

範例六:自定義 ViewGroup,仿 ScrollView

這個例子用來練手,效能上不如系統原生的 ScrollView,畢竟嵌套滑動、fling 速度計算等細節都沒處理。

public class CustomScrollView extends ViewGroup {

    private int mScreenHeight;
    private Scroller mScroller;
    private int mLastY;
    private int mStart;
    private int mEnd;

    public CustomScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        mScreenHeight = wm.getDefaultDisplay().getHeight();
        mScroller = new Scroller(getContext());
    }

    @Override
    protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
        int childCount = getChildCount();
        // 讓容器總高度等於「螢幕高度 × 子元素數量」,才能滑得動
        MarginLayoutParams mlp = (MarginLayoutParams) getLayoutParams();
        mlp.height = mScreenHeight * childCount;
        setLayoutParams(mlp);

        for (int j = 0; j < childCount; j++) {
            View child = getChildAt(j);
            if (child.getVisibility() != View.GONE) {
                child.layout(i, j * mScreenHeight, i2, (j + 1) * mScreenHeight);
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int count = getChildCount();
        for (int i = 0; i < count; ++i) {
            measureChild(getChildAt(i), widthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int y = (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mLastY = y;
                mStart = getScrollY();
                break;

            case MotionEvent.ACTION_MOVE:
                if (!mScroller.isFinished()) {
                    mScroller.abortAnimation();
                }
                int dy = mLastY - y;
                if (getScrollY() < 0) {                          // 頂部越界
                    dy = 0;
                }
                if (getScrollY() > getHeight() - mScreenHeight) { // 底部越界
                    dy = 0;
                }
                scrollBy(0, dy);
                mLastY = y;
                break;

            case MotionEvent.ACTION_UP:
                mEnd = getScrollY();
                int dScrollY = mEnd - mStart;
                if (dScrollY > 0) {
                    if (dScrollY < mScreenHeight / 3) {
                        mScroller.startScroll(0, getScrollY(), 0, -dScrollY);          // 小幅滑動,回彈
                    } else {
                        mScroller.startScroll(0, getScrollY(), 0, mScreenHeight - dScrollY); // 翻頁
                    }
                } else {
                    if (-dScrollY < mScreenHeight / 3) {
                        mScroller.startScroll(0, getScrollY(), 0, -dScrollY);
                    } else {
                        mScroller.startScroll(0, getScrollY(), 0, -mScreenHeight - dScrollY);
                    }
                }
                break;
        }
        postInvalidate();
        return true;
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if (mScroller.computeScrollOffset()) {
            scrollTo(0, mScroller.getCurrY());
        }
    }
}

使用時直接當成容器寫即可:

<com.handsome.qunyingzhuang.chapter_3.customscrollview.CustomScrollView
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        android:text="Hensen_博客(1)" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#00ff00"
        android:text="Hensen_博客(2)" />
</com.handsome.qunyingzhuang.chapter_3.customscrollview.CustomScrollView>

3.8 事件攔截機制

三個核心方法各司其職:

dispatchTouchEvent():分發事件
onInterceptTouchEvent():攔截事件(只有 ViewGroup 有)
onTouchEvent():處理事件

設三層結構:ViewGroupA 在最底、ViewGroupB 在中間、View 在最上層。四種典型流程如下。

正常情況(誰都不攔、誰都不消費):

ViewGroupA dispatchTouchEvent
  ViewGroupA onInterceptTouchEvent
    ViewGroupB dispatchTouchEvent
      ViewGroupB onInterceptTouchEvent
        View dispatchTouchEvent
          View onTouchEvent
      ViewGroupB onTouchEvent
  ViewGroupA onTouchEvent

ViewGroupB 的 onInterceptTouchEvent() 回傳 true:

ViewGroupA dispatchTouchEvent
  ViewGroupA onInterceptTouchEvent
    ViewGroupB dispatchTouchEvent
      ViewGroupB onInterceptTouchEvent   // 攔下來了
      ViewGroupB onTouchEvent            // 事件不再往下傳
  ViewGroupA onTouchEvent

View 的 onTouchEvent() 回傳 true(事件被消費):

ViewGroupA dispatchTouchEvent
  ViewGroupA onInterceptTouchEvent
    ViewGroupB dispatchTouchEvent
      ViewGroupB onInterceptTouchEvent
        View dispatchTouchEvent
          View onTouchEvent              // 到此結束,不再回傳

ViewGroupB 的 onTouchEvent() 回傳 true:

ViewGroupA dispatchTouchEvent
  ViewGroupA onInterceptTouchEvent
    ViewGroupB dispatchTouchEvent
      ViewGroupB onInterceptTouchEvent
        View dispatchTouchEvent
          View onTouchEvent
      ViewGroupB onTouchEvent            // B 接手處理

一句話總結:dispatchTouchEvent 與 onInterceptTouchEvent 由上往下逐層下發,onTouchEvent 則由下往上逐層回傳。只要某一層消費了事件(onTouchEvent 回傳 true),回傳鏈就中斷;而 onInterceptTouchEvent 回傳 true 則是提前把事件攔在自己手上,後續 MOVE、UP 都不會再往下傳。

原始碼下載:
github:https://github.com/CSDNHensen/QunYingZhuang

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved