如何将RelativeLayout绘制到canvas?

How to draw RelativeLayout to canvas?

我想画一个 RelativeLayout 的 children 到 Canvas

这就是我一直在尝试做的事情:

    // from View constructor
    container = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.containerLayout, null);

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        container.layout(0,0, w, h);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawRGB(0, 0, 0);
        container.draw(canvas);
    }

我调试并看到 onSizeChanged 被调用时具有良好的值。此代码也适用于 ImageView,那么 RelativeLayout 有何不同?

我的问题是它没有在屏幕上绘制,我没有看到它的任何内容 children。如何解决?

查看下面的示例。 它在我这边工作正常

RelativeLayout layout = new RelativeLayout(getContext());
TextView textView = new TextView(getContext());
textView.setVisibility(View.VISIBLE);
textView.setText("This is example");
layout.addView(textView);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);

layout.measure(canvas.getWidth(), canvas.getHeight());
layout.layout(0, 0, canvas.getWidth(), canvas.getHeight());
layout.draw(canvas);

添加 RelativeLAyout.mesure() 解决问题。

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    container.measure(w, h);
    container.layout(0,0, w, h);
}