一、View的生命周期
1、onMeasure:設置View的測量尺寸,對應 xml 文件中的布局寬高模式以及 getWidth()、getHeight() 等
2、onLayout:ViewGroup 中的子 View 安排位置,對應 xml 文件中的布局文件結構以及 layout() 方法
3、onDraw:繪製自己,支持自定義繪製。
二、View的測量
1、測量模式:EXACTLY(具體大小)、AT_MOST(wrap_content)、UNSPECIFIED(設置為 0)
2、測量過程
@Override protected void onMeasure(int widthMeasureSpec, int 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) { width = widthSize; } else { // 對於 match_parent 或者未指定大小的控件,使用默認值,比如控件的最低寬度等。 } if (heightMode == MeasureSpec.EXACTLY) { height = heightSize; } else { // 同上,根據測量模式計算出尺寸,對於自適應大小的控件,尺寸為默認值。 } setMeasuredDimension(width, height); }
三、View的布局
1、ViewGroup 需要實現 onLayout() 方法,對子 View 進行布局。
2、可以通過 getMeasuredWidth()、getMeasuredHeight()、getWidth()、getHeight() 等方法獲得尺寸信息。
3、可以通過 getChildCount()、getChildAt(int index)、removeView(View view)、addView(View view) 等方法對子 View 進行操作。
@Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int childCount = getChildCount(); int topOffset = 0; for (int i = 0; i < childCount; i++) { View childView = getChildAt(i); // 對於一些不想佔用區域的控件,可以通過 childView.getVisibility() 等判斷。 if (childView.getVisibility() == VISIBLE) { int childWidth = childView.getMeasuredWidth(); int childHeight = childView.getMeasuredHeight(); childView.layout(0, topOffset, childWidth, topOffset + childHeight); topOffset += childHeight; } } }
四、View的繪製
1、View 首先會調用 onDraw(Canvas canvas) 方法,傳入一個 Canvas 對象,讓開發人員自行繪製。
2、如果不重寫 onDraw,則 View 會直接繪製自己的背景以及指定的 Drawable。
3、View 的繪製和布局都是在 UI 線程中執行,因此需要注意 UI 線程的性能。
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 自定義繪製 Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.GREEN); canvas.drawCircle(getWidth() / 2f, getHeight() / 2f, getWidth() / 2f, paint); }
五、View的繪製流程總結
View 的繪製流程可以概括為:以 onDraw 為核心在 UI 線程中繪製 View,調用 onMeasure 和 onLayout 方法給出 View 的尺寸和位置。
通過了解 View 的生命周期、測量、布局、繪製等方面,可以更好地理解 Android 的 View 操作,從而更加靈活地開發。
原創文章,作者:CWZUL,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/332419.html