Reputation: 156
I am trying to draw views dynamically on click of button.On clicking the button,I got an illegal state exception
saying; the specified view already has a parent.
Is this the right way to create views dynamically?
@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 );
}
}
Upvotes: 3
Views: 7665
Reputation: 1477
The problem with this
relativeLayout.addView(draw);
setContentView(draw);
You can add a view to only one layout at a time. You can't add the same View to multiple ViewGroups (Layouts). The code above add the 'draw' View as a child of the 'relativeLayout' when sets it as the content View (for whatever class 'this.' is).
You can add the View with either:
relativeLayout.addView(draw);
or
setContentView(draw);
Upvotes: 1
Reputation: 1294
Replace
relativeLayout.addView(draw);
setContentView(draw);
with
relativeLayout.addView(draw);
relativeLayout.invalidate();
this will add your view into relativeLayout and invalidate it to refresh screen
Upvotes: 3