我试图在单击按钮时动态绘制视图。单击按钮时,我有illegal state exception
一句话;指定的视图已经有一个父视图。
这是动态创建视图的正确方法吗?
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
draw = new DrawView(this);
relativeLayout = new RelativeLayout(this);
createButton = new Button(this);
relativeLayout.addView(createButton);
setContentView(relativeLayout);
createButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
relativeLayout.addView(draw);
setContentView(draw);
}
});
}
public class DrawView extends View
{
Paint paint;
public DrawView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public DrawView(Context context)
{
super(context);
paint = new Paint();
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
paint.setColor(Color.BLACK);
paint.setStrokeWidth(3);
canvas.drawRect(30, 30, 80, 80, paint);
paint.setStrokeWidth(0);
paint.setColor(Color.CYAN);
canvas.drawRect(33, 60, 77, 77, paint );
paint.setColor(Color.YELLOW);
canvas.drawRect(33, 33, 77, 60, paint );
}
}