如果在android中覆盖了Viewgroups的dispatchDraw方法,则ImageViews是不可见的

时间:2015-12-14 06:55:22

标签: android android-custom-view

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

我已经覆盖了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);

}
}

1 个答案:

答案 0 :(得分:4)

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

只有一行:

more |= drawChild(canvas, transientChild, drawingTime);
如你所见,孩子们被吸引到那里。 因此,如果您不调用dispatchDraw的超级方法,则可能不会绘制子项。

只需致电:

super.dispatchDraw(canvas);