Android群英傳知識點回顧——第三章:Android控件架構與自定義控件詳解
知識點目錄
- 3.1 Android控件架構
- 3.2 View的測量
- 3.3 View的繪制
- 3.4 ViewGroup的測量
- 3.5 ViewGroup的繪制
- 3.6 自定義View
- 3.6.1 對現有的空間進行拓展
- 3.6.2 建立複合控件
- 3.6.3 重寫View來實作全新的空間
- 3.7 自定義ViewGroup
- 3.8 事件攔截機制分析
知識點回顧
3.1 Android控件架構
控件大緻非為兩類:UI界面架構:
- view控件:視圖控件
- viewGroup控件:包含多個View控件,并管理其包含的View控件
- 兩者之間的關系:上層控件負責下層子控件的測量與繪制,并傳遞互動事件
- Activity都包含一個Window對象,通常由PhoneWindow來實作
- PhoneWindow将一個DecorView設定為整個應用視窗的根View
- DecorView為整個Window界面的最頂層View
- DecorView隻有一個子元素為LinearLayout,代表整個Window界面,包含通知欄,标題欄,内容顯示欄三塊區域
- LinearLayout裡有兩個FrameLayout子元素:
- 标題欄顯示界面。隻有一個TextView顯示應用的名稱
- 内容欄顯示界面。就是setContentView()方法載入的布局界面
3.2 View的測量
MeasureSpec類:32位的int值,高2位為測量模式,低30位為測量大小
MeasureSpec模式:
- EXACTLY:精确模式 ,當控件的layout_width屬性或layout_height屬性指定為具體值,控件大小也是該具體值
- AT_MOST:最大值模式,當控件layout_width屬性或layout_height屬性指定為warp_content時,控件的尺寸不要超過父控件允許的最大尺寸
- UNSPECIFIED:未指定模式,控件要多大就多大,通常情況下再繪制自定義View中才會使用
View類預設的onMeasure()方法隻支援EXACTLY模式,View需要支援warp_content屬性,那麼就必須重寫onMeasure()方法,來制定warp_content的大小
下面我們通過一個簡單的執行個體,示範如何進行View的測量,首先,需要重寫onMeasure()方法:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
可以發現,onMeasure方法調用了父類的onMeasure方法,代碼跟蹤父類onMeasure方法
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
可以發現,系統最終會調用setMeasuredDimension(int measuredWidth,int measuredHeight)方法将測量後的寬高值設定進去,我們調用自定義的measureWidth()方法和measureHeight()方法,分别對寬高進行重新定義
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measureWidth(widthMeasureSpec),measureHeight(heightMeasureSpec));
}
下面以measureWidth()方法為例:
第一步:從MeasureSpec對象中提取出具體的測量模式和大小
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
第二步:通過不同的測量模式給出不同的測量值:下面這段代碼基本上可以作為模闆代碼:
- EXACTLY:使用指定的specSize即可
- AT_MOST:取出我們指定的大小和SpecSize的最小值
- UNSPECIFIED:200px
private int measureWidth(int measureSpec) {
int result = ;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = ;
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
可以發現,當指定warp_content屬性時,View就獲得一個預設值200px
3.3 View的繪制
當測量好了一個View之後,我們通過重寫View類中的onDraw()方法來繪圖,要想繪制相應的圖像,就必須在Canvas上進行繪制
Canvas就像是一個畫闆,我們傳進去一個bitmap,通過這個bitmap建立的Canvas畫布緊緊聯系在一起,這個過程我們稱之為裝載畫布,這個bitmap用來存儲所有繪制在Canvas上的像素資訊,是以當你在後面調用所有的Canvas.drawxxx方法都會發生在這個bitmap上
3.4 ViewGroup的測量
ViewGroup在測量時通過周遊所有子View,進而調用子View的Measure方法來獲得每一個子View的結果
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int childCount = getChildCount();
for (int i = ; i < childCount; i++) {
getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
}
}
ViewGroup測量完畢後,通常會去重寫onLayout()方法來控制其子View顯示位置的邏輯
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for (int i = ; i < getChildCount(); i++) {
this.getChildAt(i).layout(l, t, r, b);
}
}
3.5 ViewGroup的繪制
ViewGroup通常不需要繪制,如果不是指定ViewGroup的背景顔色,那麼ViewGroup的onDraw()方法都不會被調用,但是,ViewGroup會使用dispatchDraw()方法來繪制子View
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
}
3.6 自定義View
在View中通常有以下一些重要的回調方法:通常情況下,有以下三種方法來實作自定義的控件:
- onFinishInflate():從XML加載元件後回調
- onSizeChanged():元件大小改變時回調
- onMeasure():回調該方法來進行測量
- onLayout():回調該方法來确定顯示的位置
- onTouchEvent():監聽到觸摸事件時回調
- 對現有的控件進行拓展
- 通過組合來實作新的控件
- 重寫View來實作全新的控件
3.6.1 對現有的控件進行拓展
- 自定義修改TextView……見經典代碼回顧,案例一
- 閃動的文字效果……見經典代碼回顧,案例二
3.6.2 建立複合控件
- 自定義ToolBar的實作……見經典代碼回顧,案例三
3.6.3 重寫View來實作全新的控件
- 弧線展示圖……見經典代碼回顧,案例四
- 音頻條形圖……見經典代碼回顧,案例五
3.7 自定義ViewGroup
- 自定義ViewGroup,仿ScrollView……見經典代碼回顧,案例六
3.8 事件攔截機制分析
事件攔截機制三個重要方法舉一個例子說明事件分發機制:
- dispatchTouchEvent():分發事件
- onInterceptTouchEvent():攔截事件
- onTouchEvent():處理事件
正常的事件分發機制流程:
- ViewGroupA:處于視圖最下層
- ViewGroupB:處于視圖中間層
- View:處于視圖最上層
若ViewGroupB的onInterceptTouchEvent()方法傳回true的分發機制流程:
- ViewGroupA dispatchTouchEvent
- ViewGroupA onInterceptTouchEvent
- ViewGroupB dispatchTouchEvent
- ViewGroupB onInterceptTouchEvent
- View dispatchTouchEvent
- View onTouchEvent
- ViewGroupB onTouchEvent
- ViewGroupA onTouchEvent
若View的onTouchEvent()方法傳回true的分發機制流程:
- ViewGroupA dispatchTouchEvent
- ViewGroupA onInterceptTouchEvent
- ViewGroupB dispatchTouchEvent
- ViewGroupB onInterceptTouchEvent
- ViewGroupB onTouchEvent
- ViewGroupA onTouchEvent
若ViewGroupB的onTouchEvent()方法傳回true的分發機制流程:
- ViewGroupA dispatchTouchEvent
- ViewGroupA onInterceptTouchEvent
- ViewGroupB dispatchTouchEvent
- ViewGroupB onInterceptTouchEvent
- View dispatchTouchEvent
- View onTouchEvent
簡單的說dispatchTouchEvent()和onInterceptTouchEvent()是從下往上一層一層分發下去的,而onTouchEvent()是從上往下一層一層分發下去的
- ViewGroupA dispatchTouchEvent
- ViewGroupA onInterceptTouchEvent
- ViewGroupB dispatchTouchEvent
- ViewGroupB onInterceptTouchEvent
- View dispatchTouchEvent
- View onTouchEvent
- ViewGroupB onTouchEvent
經典代碼回顧
案例一:自定義修改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(, , getMeasuredWidth(), getMeasuredHeight(), paint1);
//繪制内層矩形
canvas.drawRect(, , getMeasuredWidth() - , getMeasuredHeight() - , paint2);
canvas.save();
//繪制文字前平移10像素
canvas.translate(, );
//父類完成的方法,即繪制文本
super.onDraw(canvas);
canvas.restore();
}
}
效果圖
案例二:閃動的文字效果
public class FlashTextView extends TextView {
int mViewWidth = ;
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 == ) {
mViewWidth = getMeasuredWidth();
if (mViewWidth > ) {
mPaint = getPaint();
mLinearGradient = new LinearGradient(, , mViewWidth, , new int[]{Color.BLUE, , 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 + ;
if (mTranslate > * mViewWidth / ) {
mTranslate = -mViewWidth;
}
matrix.setTranslate(mTranslate, );
mLinearGradient.setLocalMatrix(matrix);
postInvalidateDelayed();
}
}
}
效果圖
案例三:自定義ToolBar的實作
在values檔案夾中建立一個attrs.xml檔案來自定義屬性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TopBar">
<attr name="title" format="string" />
<attr name="titleTextSize" format="dimension" />
<attr name="titleTextColor" format="color" />
<attr name="leftTextColor" format="color" />
<attr name="leftBackground" format="reference|color" />
<attr name="leftText" format="string" />
<attr name="rightTextColor" format="color" />
<attr name="rightBackground" format="reference|color" />
<attr name="rightText" format="string" />
</declare-styleable>
</resources>
開始建立我們的ToolBar
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);
//通過這個方法,将你在attrs.xml檔案中定義的declare-styleable
//的所有屬性的值存儲到TypedArray中
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TopBar);
//從TypedArray中取出對應的值來設定的屬性指派
mLeftTextColor = ta.getColor(R.styleable.TopBar_leftTextColor, );
mLeftBackground = ta.getDrawable(R.styleable.TopBar_leftBackground);
mLeftText = ta.getString(R.styleable.TopBar_leftText);
mRightTextColor = ta.getColor(R.styleable.TopBar_rightTextColor, );
mRightBackgroup = ta.getDrawable(R.styleable.TopBar_rightBackground);
mRightText = ta.getString(R.styleable.TopBar_rightText);
mTitleTextSize = ta.getDimension(R.styleable.TopBar_titleTextSize, );
mTitleTextColor = ta.getColor(R.styleable.TopBar_titleTextColor, );
mTitle = ta.getString(R.styleable.TopBar_title);
//擷取完TypedArray的值之後,一般要調用recycle方法來避免重複建立時候的錯誤
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 version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.handsome.qunyingzhuang.chapter_3.ToolBar.ToolBar xmlns:custom="http://schemas.android.com/apk/res-auto"
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 = ;
private float mSweepValue = ;
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 / ;
mRadius = (float) (length * / );
mCirclePaint = new Paint();
mCirclePaint.setColor(Color.BLUE);
mArcPaint = new Paint();
mArcPaint.setStrokeWidth();
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 * ), (float) (length * ), (float) (length * ), (float) (length * ));
//繪制圓
canvas.drawCircle(mCircleXY, mCircleXY, mRadius, mCirclePaint);
//繪制弧線
canvas.drawArc(mArcRectF, , mSweepValue, false, mArcPaint);
//繪制文字
canvas.drawText(mShowText, , mShowText.length(), mCircleXY, mCircleXY + (mTextSize / ), mTextPaint);
}
public void setSweepValue(float sweepValue) {
if (sweepValue != ) {
mSweepValue = sweepValue;
} else {
mSweepValue = ;
}
invalidate();
}
}
當使用者不指定具體的比例值時,可以調用以下代碼來設定相應的比例值
CircleProgressView circleProgressView = (CircleProgressView) findViewById(R.id.circle);
circleProgressView.setSweepValue();
效果圖
案例五:音頻條形圖
public class MusicView extends View {
private int mWidth;
private int mRectHeight;
private int mRectWidth;
private int mRectCount = ;
private LinearGradient mLinearGradient;
private Paint mPaint=new Paint();
private float currentHeight;
private int offset = ;
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 * / mRectCount);
mLinearGradient = new LinearGradient(, , mRectWidth, mRectHeight, Color.YELLOW, Color.BLUE, Shader.TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//周遊繪制矩形,留中間間隔
for (int i = ; i < mRectCount; i++) {
//開始繪制
canvas.drawRect((float) (mWidth * / + mRectWidth * i + offset),
currentHeight, (float) (mWidth * / + mRectWidth * (i + )), mRectHeight, mPaint);
}
//擷取随機數
mRandom = Math.random();
currentHeight = ((float) (mRectHeight * mRandom));
//延遲300去重新整理
postInvalidateDelayed();
}
}
效果圖
案例六:自定義ViewGroup,仿ScrollView
自定義的ScrollView沒有系統自帶的性能好,畢竟很多因素都沒考慮到,這裡隻是适用于練手使用
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 = ; j < childCount; j++) {
View child = getChildAt(j);
if (child.getVisibility() != View.GONE) {
child.layout(i, j * mScreenHeight, i2, (j + ) * mScreenHeight);
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int count = getChildCount();
for (int i = ; i < count; ++i) {
View childView = getChildAt(i);
measureChild(childView, 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() < ) {
dy = ;
}
if (getScrollY() > getHeight() - mScreenHeight) {
dy = ;
}
scrollBy(, dy);
mLastY = y;
break;
case MotionEvent.ACTION_UP:
mEnd = getScrollY();
int dScrollY = mEnd - mStart;
if (dScrollY > ) {
if (dScrollY < mScreenHeight / ) {
mScroller.startScroll(, getScrollY(), , -dScrollY);
} else {
mScroller.startScroll(, getScrollY(), , mScreenHeight - dScrollY);
}
} else {
if (-dScrollY < mScreenHeight / ) {
mScroller.startScroll(, getScrollY(), , -dScrollY);
} else {
mScroller.startScroll(, getScrollY(), , -mScreenHeight - dScrollY);
}
}
break;
}
postInvalidate();
return true;
}
@Override
public void computeScroll() {
super.computeScroll();
if (mScroller.computeScrollOffset()) {
scrollTo(, mScroller.getCurrY());
}
}
}
在布局中使用
<?xml version="1.0" encoding="utf-8"?>
<com.handsome.qunyingzhuang.chapter_3.CustomScrollView.CustomScrollView
xmlns:android="http://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>
效果圖
經典回顧源碼下載下傳
github:https://github.com/CSDNHensen/QunYingZhuang