編輯:關於 Android 程式設計
最關鍵的是 onTouchEvent 這個方法。接下來還會介紹更多與事件相關的知識(比如事件分發),這裡先聚焦最簡單的觸控事件。
單指有四個動作,再加上 x 值與 y 值。
@Override public boolean onTouchEvent(MotionEvent event) { return super.onTouchEvent(event); }重寫 onTouchEvent 即可,裡面包含一組事件,分別是:
MotionEvent.ACTION_DOWN:手指按下;
MotionEvent.ACTION_MOVE:手指移動;
ACTION_UP:手指抬起;
ACTION_CANCEL:取消(表面上看與 UP 沒什麼區別,實際與事件分發有關,這裡暫不展開)。
以上就是簡單介紹,接下來實現一個案例——簡單的畫畫板。
package com.zhouzhou.flowlayoutdemo; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.util.AttributeSet; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; /** * Created by zhousaito on 2016/9/7. */ public class TouchView extends View { private Paint mPaint; private Path mPath; private float mLastX; private float mLastY; private int mPenColor; private int mPenSize; public TouchView(Context context) { this(context, null); } public TouchView(Context context, AttributeSet attrs) { this(context, attrs, R.style.MyDefStyle); } public TouchView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TouchView, defStyleAttr, R.style.MyDefStyle); for (int i = 0; i < array.getIndexCount(); i++) { int index = array.getIndex(i); switch (index) { case R.styleable.TouchView_penColor: mPenColor = array.getColor(index, Color.RED); break; case R.styleable.TouchView_penSize: mPenSize = array.getDimensionPixelSize(index, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics())); break; } } mPaint = new Paint(); mPath = new Path(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawColor(Color.WHITE); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(mPenSize); mPaint.setColor(mPenColor); //畫上線條 canvas.drawPath(mPath,mPaint); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mLastX = event.getX(); mLastY = event.getY(); mPath.moveTo(mLastX, mLastY); break; case MotionEvent.ACTION_MOVE: mPath.lineTo(event.getX(), event.getY()); mLastX = event.getX(); mLastY = event.getY(); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: break; } //重寫繪制 invalidate(); return true; } }
這裡添加了一些自定義屬性與 style。首先在 attrs.xml 中定義:
然後在代碼中引用即可,這樣一個簡單的畫板就完成了。
接下來了解 Matrix API。用圖示來理解,Matrix(矩陣)主要有幾種變換方式:
1. 縮放:mMatrix.postScale(0.5f, 0.5f, 100, 100),前兩個參數是縮放比例,後兩個是中心點,不寫則繞父控件左上角縮放;
2. 旋轉:mMatrix.postRotate(10, 100, 100),用法與縮放類似;
3. 平移:mMatrix.postTranslate(10, 10),即移動;
4. 傾斜:mMatrix.postSkew(0.1f, 0)。
前幾個屬性比較直觀,網上資料也很多,其實在屬性動畫中已有接觸,只有傾斜較少用到。
此處判斷依據並非 event.getAction(),而是 event.getActionMasked(),用它來判斷是否為多手指觸控:
MotionEvent.ACTION_POINTER_DOWN:按下;
MotionEvent.ACTION_MOVE:移動(與單指一致);
MotionEvent.ACTION_POINTER_UP:抬起。
與單指衝突時,可通過 event.getPointerCount() 判斷手指數量,再做相應處理。
本節嘗試繼承 ViewGroup 來實現自定義控件——FlowLayout(流式布局)。核心要點如下:
[1] TODO --> onLayout() -->裡面的值 [2] 用 recycleView 來實現一個流式布局 [3] 必須到 onMeasure 中寫 measureChildren(); 才可以顯示,不然不能顯示
第一步,繼承 ViewGroup:
public class FlowLayout extends ViewGroup { public FlowLayout(Context context) { super(context); } public FlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } }由於我們的目標是實現流式布局,因此按需編寫 onLayout 與 onMeasure。初版 onLayout 從左到右排列子控件,並在 onMeasure 中調用 measureChildren:
/** * MeasureSpec.UNSPECIFIED * --->子控件自己的大小來顯示,所以怎麼設置值都沒什麼用 * 二級緩存繪制 * [1] TODO --> onLayout() -->裡面的值 * [2] 用 recycleView 來實現一個流式布局 * [3] 必須到 onMeasure 中寫 measureChildren(); 才可以顯示,不然不能顯示 * @param changed * @param l 父控件的位置 * @param t * @param r * @param b */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { //流式布局 從左邊到右邊開始排 int left = l; int maxHeight =0; int top = t; //總寬度 int width = r - l; for (int i = 0; i < getChildCount(); i++) { //得到子類控件 View view = getChildAt(i); // if (left + view.getMeasuredWidth() > width) { top += maxHeight; maxHeight=0; left =l; } view.layout(left,top,left+view.getMeasuredWidth(),top+view.getMeasuredHeight()); left+=view.getMeasuredWidth(); maxHeight = Math.max(maxHeight, view.getMeasuredHeight()); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { /** * 要寫這個才能顯示 */ // measureChildren(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); measureChildren(widthMeasureSpec,heightMeasureSpec); super.onMeasure(widthMeasureSpec, heightMeasureSpec); }這樣大致實現了一版,但由於沒有重寫 onMeasure 來計算自身寬高,FlowLayout 的寬高會充滿父控件(表現等同 match_parent)。

若給 FlowLayout 加上 padding,就能看出工程尚未完成(布局由 6 個 TextView 與 6 個機器人圖標交錯組成):

此時發現沒有處理 padding 與 margin。改進後的 onLayout 如下:
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int left = getPaddingLeft(); int maxHeight = 0; int top = getPaddingTop(); int width = r - l - getPaddingLeft() - getPaddingRight(); for (int i = 0; i < getChildCount(); i++) { View view = getChildAt(i); MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams(); if (left + view.getMeasuredWidth() > width) { top += maxHeight; maxHeight = 0; left = getPaddingLeft(); } view.layout(left + params.leftMargin, top + params.topMargin, left + params.leftMargin + view.getMeasuredWidth(), top + params.topMargin + view.getMeasuredHeight()); left += view.getMeasuredWidth() + params.leftMargin + params.rightMargin; maxHeight = Math.max(maxHeight, view.getMeasuredHeight() + params.topMargin + params.bottomMargin); } }加上 padding 處理後的效果(去掉背景更易觀看):

接著補上 onMeasure 方法,決定父控件自身的寬高,這樣就能像普通布局一樣使用了:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { /** * 要寫這個才能顯示 */ // measureChildren(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); measureChildren(widthMeasureSpec, heightMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width = 0; int height = 0; //只要不是固定的 就 if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY) { int left = getPaddingLeft(); int maxHeight = 0; int top = getPaddingTop(); for (int i = 0; i < getChildCount(); i++) { View view = getChildAt(i); MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams(); //相加後,通過原來的 if (left + view.getMeasuredWidth() + params.rightMargin + params.leftMargin > widthSize - getPaddingRight()) { top += maxHeight; maxHeight = 0; //在這裡得到的是 left 的,相當於這排排滿了的最大寬度 width = Math.max(width, left); left = getPaddingLeft(); } left += view.getMeasuredWidth() + params.rightMargin + params.leftMargin; maxHeight = Math.max(maxHeight, view.getMeasuredHeight() + params.topMargin + params.bottomMargin); } height = maxHeight + top + getPaddingTop() + getPaddingBottom(); switch (widthMode) { case MeasureSpec.AT_MOST: width = Math.min(width,widthSize); break; case MeasureSpec.UNSPECIFIED: width = widthSize; break; } switch (heightMode) { case MeasureSpec.AT_MOST: //容器的高度 height = Math.min(heightSize, height); break; case MeasureSpec.UNSPECIFIED: //容器的高度 height = heightSize; break; } }else { //固定的就用自己固定的高和寬 width =widthSize; height = heightSize; } setMeasuredDimension(width, height); // super.onMeasure(widthMeasureSpec, heightMeasureSpec); }寫完這些,基本就完成了——通過繼承 ViewGroup 實現了一個簡單的流式容器 FlowLayout,效果如下:

雖然樣式還比較樸素,但整個自定義流程已經跑通了。以上就是今天的學習內容,記錄一下這兩個多小時的積累。
Android 模擬地理位置實作指南(相容 Android 6.0 以上)
一、開啟系統的模擬位置 Android 6.0 以下:進入【開發者選項 → 允許模擬位置】。 Android 6.0 及以上:選項改為【開發者選項 → 選擇模擬位置資訊
從源碼徹底搞懂 Android 事件分發機制
事件分發在 Android 裡舉足輕重。滑動衝突、下拉刷新、嵌套滑動,任何一個場景都需要你把分發機制想得足夠透徹,才能寫出正確的處理邏輯。我曾經以為自己已經很清楚了,也寫
Android RadioGroup 單選按鈕使用詳解
先看效果單選按鈕是表單與設定頁面中常見的元件。Android 通常以 RadioGroup 搭配多個 RadioButton 來實作,讓同一群組中的選項只能有一個被選取。
Android RatingBar 自定義星級評分樣式實作
RatingBar 是在 SeekBar 與 ProgressBar 基礎上延伸而來、以星形呈現等級的元件。使用預設樣式時,使用者可以透過觸控、拖曳或按鍵來打分。它內建兩