Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a button control to an android xml view at runtime?

Tags:

android

layout

I have an android xml layout, main.xml. I would like to add controls to this layout at runtime (I would like to add a series of additional linear layouts that contain buttons controls). Can I do that and if yes, how?

Thanks

like image 752
a.p. Avatar asked Feb 07 '11 17:02

a.p.


2 Answers

I see the error u r doing here

LinearLayout mainLayout = (LinearLayout) findViewById(R.layout.main);

You r taking the layout as Linearlayout object, you should take the LinearLayout id

Try this

LinearLayout lnr = (LinearLayout) findViewById(R.id.LinearLayout01);

Button b1 = new Button(this);

b1.setText("Btn");

lnr.addView(b1);
like image 86
praveenb Avatar answered Nov 15 '22 05:11

praveenb


You can add controls programmatically if you want in your code, or even another XML with a View and an Inflater.

Here you can read the basics: http://developer.android.com/guide/topics/ui/declaring-layout.html

like image 3
Nacho L. Avatar answered Nov 15 '22 04:11

Nacho L.