Android知识Android技术知识Android开发经验谈

自定义ViewGroup不走onDraw()方法的问题

2017-07-18  本文已影响537人  浔它芉咟渡

背景

前几天,有位朋友和我说,他写的自定义的View的onDraw()方法没走,让他把代码发过来,一看他的这个自定义的View继承的是一个ViewGroup,众所周知,当我们自定义一个View时会重写他的3个方法,onMeasure(),onLayout(),onDraw()方法,但是自定义一个ViewGroup的时候要重写onMeasure(),onLayout(),dispatchDraw()这3个方法。当我告诉他的时候问题解决了。但是,他又来了一句,为啥?好吧,自己之前也没探究过这些东西,我认输,我查查!

探究

image

之前在window源码绘制流程中,最后给了这福图,其实View最后出现在手机屏幕上是通过ViewRootImpl来实现的,但是有人就说了,不是应该是调用那三个方法吗?其实调用那三个方法是说你要出现个什么形状,而具体的操作View到Window或者Activity上是在ViewRootImpl。

ViewRootImpl中有这些有关绘制的方法


image

从图中看方法名也能猜出来,performMeasure(),performLayout(),performDraw()也能想到这个不就和我们自定义View的那三个方法对应上了吗!!!哈哈哈,不能光靠猜,还是看代码吧!!!因为现在的问题是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();
        }
    ......
 }

从代码中可以看出调用了ViewRootImpl的draw方法。里面的参数是一个boolean值,判断是否要重新绘制。看下从代码中可以看出调用了ViewRootImpl的draw方法

  private void draw(boolean fullRedrawNeeded) {
       ......
        if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
                    return;
        }

        if (animating) {
            mFullRedrawNeeded = true;
            scheduleTraversals();
        }
    }

接下来调用了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);
           }
           ......
    }

看到这里终于出来了,最后调用了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;
        }
        ......
    }

从代码的注释中能清楚的看到绘制的顺序:

  1. 画背景
  2. 画canvas的图层(非必须)
  3. 画View自己
  4. 画子View
  5. 如果2执行了,这部要回复图层(非必须)

这个并不是重点,下面的这块代码才是重点:

  if (!dirtyOpaque) onDraw(canvas);//如果有背景色,走onDraw()方法,如果没有背景色,不走onDraw()方法

  // Step 4, draw the children
  dispatchDraw(canvas);

如果有背景色就会走onDraw方法。如果没有背景色,不走onDraw()方法。再结合问题。写个简单的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:执行了");
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        Log.d("tag", "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"
       >

        <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>

运行一下,看结果:


image

只执行了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>

运行一下,看结果:


image

这次看到两个方法都执行了,onDraw方法也执行了。

结论

自定义的ViewGroup并不是不会走onDraw()方法,如果有背景色是要走的。正常情况下,重写dispatchDraw就好了。

上一篇下一篇

猜你喜欢

热点阅读