背景
前幾天,有位朋友和我說,他寫的自定義的View的onDraw()方法沒走戒祠,讓他把代碼發(fā)過來,一看他的這個自定義的View繼承的是一個ViewGroup速种,眾所周知姜盈,當(dāng)我們自定義一個View時會重寫他的3個方法,onMeasure(),onLayout(),onDraw()方法哟旗,但是自定義一個ViewGroup的時候要重寫onMeasure(),onLayout(),dispatchDraw()這3個方法贩据。當(dāng)我告訴他的時候問題解決了。但是闸餐,他又來了一句饱亮,為啥?好吧舍沙,自己之前也沒探究過這些東西近上,我認輸,我查查拂铡!
探究
之前在window源碼繪制流程中壹无,最后給了這福圖,其實View最后出現(xiàn)在手機屏幕上是通過ViewRootImpl來實現(xiàn)的感帅,但是有人就說了斗锭,不是應(yīng)該是調(diào)用那三個方法嗎?其實調(diào)用那三個方法是說你要出現(xiàn)個什么形狀失球,而具體的操作View到Window或者Activity上是在ViewRootImpl岖是。
ViewRootImpl中有這些有關(guān)繪制的方法
從圖中看方法名也能猜出來,performMeasure(),performLayout(),performDraw()也能想到這個不就和我們自定義View的那三個方法對應(yīng)上了嗎J蛋2虺拧!哈哈哈黔牵,不能光靠猜聪轿,還是看代碼吧!;帧陆错!因為現(xiàn)在的問題是Draw()方法不能用,所以我們只看performDraw()方法金赦。
private void performDraw() {
if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) {
return;
}
final boolean fullRedrawNeeded = mFullRedrawNeeded;
mFullRedrawNeeded = false;
mIsDrawing = true;
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
try {
draw(fullRedrawNeeded);
} finally {
mIsDrawing = false;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
// For whatever reason we didn't create a HardwareRenderer, end any
// hardware animations that are now dangling
if (mAttachInfo.mPendingAnimatingRenderNodes != null) {
final int count = mAttachInfo.mPendingAnimatingRenderNodes.size();
for (int i = 0; i < count; i++) {
mAttachInfo.mPendingAnimatingRenderNodes.get(i).endAllAnimators();
}
mAttachInfo.mPendingAnimatingRenderNodes.clear();
}
......
}
從代碼中可以看出調(diào)用了ViewRootImpl的draw方法危号。里面的參數(shù)是一個boolean值,判斷是否要重新繪制素邪⊥饬看下從代碼中可以看出調(diào)用了ViewRootImpl的draw方法
private void draw(boolean fullRedrawNeeded) {
......
if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
return;
}
if (animating) {
mFullRedrawNeeded = true;
scheduleTraversals();
}
}
接下來調(diào)用了ViewRootImpl的drawSoftware()方法:
private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
boolean scalingRequired, Rect dirty) {
......
try {
canvas.translate(-xoff, -yoff);
if (mTranslator != null) {
mTranslator.translateCanvas(canvas);
}
canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
attachInfo.mSetIgnoreDirtyState = false;
mView.draw(canvas);
drawAccessibilityFocusedDrawableIfNeeded(canvas);
}
......
}
看到這里終于出來了,最后調(diào)用了View.draw(canvas)方法。跳入View中的onDraw()方法來看看偷线。
public void draw(Canvas canvas) {
final int privateFlags = mPrivateFlags;
final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
(mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
/*
* Draw traversal performs several drawing steps which must be executed
* in the appropriate order:
*
* 1. Draw the background
* 2. If necessary, save the canvas' layers to prepare for fading
* 3. Draw view's content
* 4. Draw children
* 5. If necessary, draw the fading edges and restore layers
* 6. Draw decorations (scrollbars for instance)
*/
// Step 1, draw the background, if needed
int saveCount;
if (!dirtyOpaque) {
drawBackground(canvas);
}
// skip step 2 & 5 if possible (common case)
final int viewFlags = mViewFlags;
boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
if (!verticalEdges && !horizontalEdges) {
// Step 3, draw the content
if (!dirtyOpaque) onDraw(canvas);//如果有背景色磨确,走onDraw()方法,如果沒有背景色声邦,不走onDraw()方法
// Step 4, draw the children
dispatchDraw(canvas);
// Overlay is part of the content and draws beneath Foreground
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().dispatchDraw(canvas);
}
// Step 6, draw decorations (foreground, scrollbars)
onDrawForeground(canvas);
// we're done...
return;
}
......
}
從代碼的注釋中能清楚的看到繪制的順序:
- 畫背景
- 畫canvas的圖層(非必須)
- 畫View自己
- 畫子View
- 如果2執(zhí)行了乏奥,這部要回復(fù)圖層(非必須)
這個并不是重點,下面的這塊代碼才是重點:
if (!dirtyOpaque) onDraw(canvas);//如果有背景色亥曹,走onDraw()方法邓了,如果沒有背景色,不走onDraw()方法
// Step 4, draw the children
dispatchDraw(canvas);
如果有背景色就會走onDraw方法媳瞪。如果沒有背景色骗炉,不走onDraw()方法。再結(jié)合問題蛇受。寫個簡單的demo驗證一下句葵。
自定義一個ViewGroup:
/**
* Created by xinchang on 2017/7/18.
*/
public class MyViewGroup extends ViewGroup {
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d("tag", "onDraw:執(zhí)行了");
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
Log.d("tag", "dispatchDraw:執(zhí)行了");
}
}
第一次:不給MyViewGroup添加背景色:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="cx.com.hellotinker.MainActivity">
<cx.com.hellotinker.MyView
android:layout_width="wrap_content"
android:layout_height="match_parent"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</cx.com.hellotinker.MyView>
</android.support.constraint.ConstraintLayout>
運行一下,看結(jié)果:
只執(zhí)行了dispatchDraw()這個方法
改下布局文件兢仰,給MyViewGroup添加一個背景色:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="cx.com.hellotinker.MainActivity">
<cx.com.hellotinker.MyView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#00ff00"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</cx.com.hellotinker.MyView>
</android.support.constraint.ConstraintLayout>
運行一下乍丈,看結(jié)果:
這次看到兩個方法都執(zhí)行了,onDraw方法也執(zhí)行了把将。
結(jié)論
自定義的ViewGroup并不是不會走onDraw()方法轻专,如果有背景色是要走的。正常情況下察蹲,重寫dispatchDraw就好了铭若。