ViewGroup中绘制背景drawable的方式

Which way background drawable is drawn in ViewGroup

By default, onDraw() isn't called for ViewGroup.

所以我有一个问题:当我们为 ViewGroup 设置可绘制背景时会发生什么

onDraw() 继承自 View class,因为 ViewGroup 是 View 的子class。因此,当您在 ViewGroup 上设置背景时,它的工作方式与任何其他视图相同。当您在视图上调用 setBackground 时,它会将 requestLayout 标志设置为 true 并使视图无效。

此外,View class 的官方文档指出:

If you set a background drawable for a View, then the View will draw it before calling back to its onDraw() method.

您可以在 Android 的视图 class

的源代码中看到它是如何工作的
    public void setBackgroundDrawable(Drawable d) {
        ...
        {
            requestLayout = true;
        }
        ...
        computeOpaqueFlags();
        if (requestLayout) {
            requestLayout();
        }
        mBackgroundSizeChanged = true;
        invalidate(true);
    }

如果您查看 invalidate() 的文档,您会发现

public void invalidate () Invalidate the whole view. If the view is visible, onDraw(android.graphics.Canvas) will be called at some point in the future.

setBackgroundColor()setBackgroundResource() 在内部使用 setBackgroundDrawable() 所以它们的工作方式相同。

总而言之,当您执行 setBackground() 时,onDraw 会在将来的某个时刻被调用。