我试图在点击按钮时动态绘制视图。点击按钮,我得到一个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 );
}
}
答案 0 :(得分:3)
替换
relativeLayout.addView(draw);
setContentView(draw);
带
relativeLayout.addView(draw);
relativeLayout.invalidate();
这会将您的视图添加到 relativeLayout 并使其无效以刷新屏幕
答案 1 :(得分:1)
这个问题
relativeLayout.addView(draw);
setContentView(draw);
您一次只能将视图添加到一个布局。您无法将同一视图添加到多个ViewGroups(布局)。上面的代码将'draw'视图添加为'relativeLayout'的子项时将其设置为内容视图(对于任何类'this。'是)。
您可以使用以下任一方式添加视图:
relativeLayout.addView(draw);
或
setContentView(draw);