3

我试图在单击按钮时动态绘制视图。单击按钮时,我有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 );
    }
}
4

2 回答 2

3

代替

     relativeLayout.addView(draw);
     setContentView(draw);

     relativeLayout.addView(draw);
     relativeLayout.invalidate();

这会将您的视图添加到relativeLayout并使其无效以刷新屏幕

于 2013-09-13T06:20:38.023 回答
1

这个问题

relativeLayout.addView(draw);
setContentView(draw);

您一次只能将视图添加到一个布局。您不能将相同的视图添加到多个视图组(布局)。上面的代码在将“draw”视图设置为内容视图时将其添加为“relativeLayout”的子视图(对于任何类“this.”)。

您可以使用以下任一方式添加视图:

 relativeLayout.addView(draw);

或者

 setContentView(draw);
于 2013-09-13T06:13:36.733 回答