Dynamically adding widgets to a User interface

Normally the views defined using the XML layout field can be simply inflated by using the setContetntView(R.layout.main).

The following code is used to add a button dynamically:

public void onCreate(Bundle savedInstanceState) {

   //Inflate the layout file res\layout\activity_uc.xml

   LinearLayout layout = (LinearLayout)getLayoutInflater().inflate(R.layout.main,null);

   //Initiate a new button

   Button reset = new Button(this);
   reset.setText("Reset Form");

   //Add the new button to the layout

   layout.addView(reset,new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,


   //Attach the view to the window



Interface created using a Layout XML 

Interface created after adding a button dynamically


Creating a One activity Application


We are going to design a simple application which basically converts between different units of Measurement.  And the user can select an option from a dropdown(called Spinner in Android) and enter the quantity needed to be converted in a Textbox and click on the Convert button and the converted value is displayed in the same textbox(EditText in Android). A Clear button clears the EditText and a Close button closes the application.

We will start with a rough prototype and then build on it in future and try to improve and optimize it in different ways.

Let’s get going

Designing the interface

As can be seen from the requirements the interface would need the following widgets:

1. EditText ( Textbox)

2.TextView (Label)

3. Spinner (Dropdown box)

4. Button

Let’s design a layout in the Eclipse. Open the main.xml in the res/layout directory

And drag and drop the widgets required , start with the LinearLayout from the layouts section. Try to emulate from the highlighted section. Do not worry about the appearance too much.

Once done with the interface, name the widgets properly(By selecting the widget in Outline section and going to properties section) so that you can reference them from the code.

Once you have added the widgets, its time to launch the application and see your work of Art .;)

Of course the buttons or the spinners won’t work because we haven’t added event handlers for them.

Step 2:

Populating the Spinner widget. (Android Spinner, XML resources, Adapter)

We will be populating the Spinner using values from an XML file. This is the best way to decouple the business logic from the User interface. Android provides options to create different types of XML resources , for the time being just goto the res/values and right click on it >> New >> Android XML File

Select the Resource Type as Values and click Finish.

Copy and Paste the XML below. As can be seen from the XML file we have defined 2 arrays :

  1. conversions : Used to populate the spinner.
  2. multipliers: Used in the conversion calculation.
<?xml version="1.0" encoding="utf-8"?>


	<string-array name="conversions">

		<item>Pounds to Kgs</span></item>

		<item>Kgs</span> to Pounds</item>

		<item>Kilometers to Miles</item>

		<item>Miles to Kilometers</item>

		<item>Degrees Celsius</span> to Degrees Fahrenheit</span></item>

		<item>Degrees Fahrenheit</span> to Degrees Celsius</span></item>


	<string-array name="multipliers">


		<item>2.20462</item> <!-- Acres to Square Miles -->

		<item>0.621371</item> <!--Atmospheres to Pascals</span>  -->

		<item>1.60934</item> <!--Bars to Pascals</span> -->

		<item>0</item> <!--Degrees Celsius</span> to Degrees Fahrenheit</span> -->

		<item>0</item> <!--Degrees Fahrenheit</span> to Degrees Celsius</span>  -->



Eclipse power tip : To Beautify any code in Eclipse IDE use Ctrl+Shift + f for windows and Command + shift+ f for Mac.

Save the XML file and get back to the code window.

Add the following code

// Getting a reference to the Spinner from the layout

final Spinner spnConversions = (Spinner) findViewById(R.id.conversions);

// Creating the items from the Array resource

ArrayAdapter<CharSequence> aa = ArrayAdapter.createFromResource(this,



//Setting the spinner item look from android layouts


// Populating the spinner with the XML data


Run the application and you should see the items once you click on the small down arrow on the spinner.

Add the following code for attaching a listener to the spinner widget.

AdapterView.OnItemSelectedListener spinlistener = new OnItemSelectedListener() {

public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
//save the selected position
MainActivity.this.position = position;

public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

//attaching the listener

The code snippet saves the position of selected item. Declare a private attribute in activity named position.

Next add the listeners for the Clear and the Close buttons.

// Adding listener for the close button

Button btnClose = (Button) findViewById(R.id.close);

View.OnClickListener btnCloselistener = new View.OnClickListener() {

public void onClick(View v) {

//closing the application




// Attaching the listener to the button


// Adding listener for the close button

Button btnClear = (Button) findViewById(R.id.clear);

View.OnClickListener btnClearListener = new OnClickListener() {

public void onClick(View v) {

//clearing the text from EditText




// Attaching the listener to the button


This finishes the simple application; we will be building on the application in the next coming up tutorials.