如果 Viewgroups 的 dispatchDraw 方法在 android 中被覆盖,ImageViews 将不可见

ImageViews are invisible if Viewgroups's dispatchDraw method is overwritten in android

我写了一个自定义视图来在圆圈内动态显示图像。

我改写了Viewgroup的dispatchDraw方法来画圆。在此之后,子 ImageViews 不会显示在屏幕上,如果我不覆盖该方法,那么它们会显示在屏幕上。

这是我的 class:

public class CustomView extends RelativeLayout {

private Paint paint;
private View mView;
private Context context;


private void init(Context context) {
    LinearLayout layout = new LinearLayout(context);
    layout.setGravity(Gravity.CENTER);
    layout.setOrientation(LinearLayout.VERTICAL);

    // Set generic layout parameters
    LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

    Button button = new Button(context);
    button.setText("Button!");
    layout.addView(button, params); // Modify this

    ImageView imageView = new ImageView(context);
    imageView.setImageResource(R.drawable.coffe_selected);
    layout.addView(imageView);      

    this.addView(layout);

}

public CustomView(Context mContext) {
    super(mContext);
    context = mContext;

    // create the Paint and set its color
    paint = new Paint();
    paint.setColor(0xFF1f5b83);

    init(context);

}


@Override
protected void dispatchDraw(Canvas canvas) {
    int width = this.getWidth();
    int height = this.getHeight();
    canvas.drawCircle(width / 2, height / 2-64, 200, paint);
}


@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

}
}

查看 ViewGroup 的源代码以及 dispatchDraw 中发生的事情。

只有一行:

more |= drawChild(canvas, transientChild, drawingTime);

如你所见,孩子们被画在那里。 所以如果不调用dispatchDraw的super方法,可能childs没有画出来

只需调用:

super.dispatchDraw(canvas);