Pages

Wednesday, 11 May 2011

Adding views to a layout dynamically

How do I add a button to my layout in code?

Firstly add the appropriate import to your Activity class for the view to add, in this case a button:

import android.widget.Button;

Then create a new button object within the activity onCreate method:

Button myButton = new Button(this);
myButton.setText("Tap Me");

Finally add the button to the layout:

LinearLayout layout = (LinearLayout) findViewById(R.id.layout1);
layout.addView(myButton);

Obviously the same logic applies to other views (TextViews, etc).

You might also want to apply fonts to your controls, if so take a look at Using a True-Type Font in your Android app.

0 comments:

Post a Comment