如何使用Canvas在Android上绘制视图?

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 );
    }
}
2个回答

3

替换

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

使用

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

这将把你的视图添加到RelativeLayout中并使其失效以刷新屏幕。

1

The problem with this

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

您一次只能将视图添加到一个布局中。您不能将同一视图添加到多个ViewGroup(布局)中。上面的代码将“draw”视图作为“relativeLayout”的子项添加,当将其设置为内容视图时(对于任何类“this.”)。
您可以使用以下任一方式添加视图:
 relativeLayout.addView(draw);

or

 setContentView(draw);

对于这种情况,您需要创建多个视图并将这些视图添加到相应的布局中。 - android_dev
@Prashanth:您可以将多个视图添加到布局(ViewGroup)中,只需重复调用“.addView(View)”方法即可。问题在于将相同的视图添加到多个ViewGroup中。 - Ribo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接