我已经编写了一个自定义视图来动态显示圆内的图像。
我已经覆盖了viewgroup的dispatchdraw方法来绘制圆。在此之后,子imageviews将不会显示在屏幕上,如果我不重写该方法,则它们将显示在屏幕上。
这是我的课:

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方法,则可能不会绘制子对象。
简单呼叫:
super.dispatchDraw(canvas);

07-25 21:14