背景
前幾天,有位朋友和我說(shuō),他寫(xiě)的自定義的View的onDraw()方法沒(méi)走,讓他把代碼發(fā)過(guò)來(lái),一看他的這個(gè)自定義的View繼承的是一個(gè)ViewGroup,眾所周知,當(dāng)我們自定義一個(gè)View時(shí)會(huì)重寫(xiě)他的3個(gè)方法,onMeasure(),onLayout(),onDraw()方法,但是自定義一個(gè)ViewGroup的時(shí)候要重寫(xiě)onMeasure(),onLayout(),dispatchDraw()這3個(gè)方法。當(dāng)我告訴他的時(shí)候問(wèn)題解決了。但是,他又來(lái)了一句,為啥?好吧,自己之前也沒(méi)探究過(guò)這些東西,我認(rèn)輸,我查查!
探究

之前在window源碼繪制流程中,最后給了這福圖,其實(shí)View最后出現(xiàn)在手機(jī)屏幕上是通過(guò)ViewRootImpl來(lái)實(shí)現(xiàn)的,但是有人就說(shuō)了,不是應(yīng)該是調(diào)用那三個(gè)方法嗎?其實(shí)調(diào)用那三個(gè)方法是說(shuō)你要出現(xiàn)個(gè)什么形狀,而具體的操作View到Window或者Activity上是在ViewRootImpl。
ViewRootImpl中有這些有關(guān)繪制的方法

從圖中看方法名也能猜出來(lái),performMeasure(),performLayout(),performDraw()也能想到這個(gè)不就和我們自定義View的那三個(gè)方法對(duì)應(yīng)上了嗎?。?!哈哈哈,不能光靠猜,還是看代碼吧!??!因?yàn)楝F(xiàn)在的問(wè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ù)是一個(gè)boolean值,判斷是否要重新繪制。看下從代碼中可以看出調(diào)用了ViewRootImpl的draw方法
private void draw(boolean fullRedrawNeeded) {
......
if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
return;
}
if (animating) {
mFullRedrawNeeded = true;
scheduleTraversals();
}
}
接下來(lái)調(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);
}
......
}
看到這里終于出來(lái)了,最后調(diào)用了View.draw(canvas)方法。跳入View中的onDraw()方法來(lái)看看。
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()方法,如果沒(méi)有背景色,不走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;
}
......
}
從代碼的注釋中能清楚的看到繪制的順序:
- 畫(huà)背景
- 畫(huà)canvas的圖層(非必須)
- 畫(huà)View自己
- 畫(huà)子View
- 如果2執(zhí)行了,這部要回復(fù)圖層(非必須)
這個(gè)并不是重點(diǎn),下面的這塊代碼才是重點(diǎn):
if (!dirtyOpaque) onDraw(canvas);//如果有背景色,走onDraw()方法,如果沒(méi)有背景色,不走onDraw()方法
// Step 4, draw the children
dispatchDraw(canvas);
如果有背景色就會(huì)走onDraw方法。如果沒(méi)有背景色,不走onDraw()方法。再結(jié)合問(wèn)題。寫(xiě)個(gè)簡(jiǎn)單的demo驗(yàn)證一下。
自定義一個(gè)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>
運(yùn)行一下,看結(jié)果:

只執(zhí)行了dispatchDraw()這個(gè)方法
改下布局文件,給MyViewGroup添加一個(gè)背景色:
<?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>
運(yùn)行一下,看結(jié)果:

這次看到兩個(gè)方法都執(zhí)行了,onDraw方法也執(zhí)行了。
結(jié)論
自定義的ViewGroup并不是不會(huì)走onDraw()方法,如果有背景色是要走的。正常情況下,重寫(xiě)dispatchDraw就好了。