Saturday, June 11, 2011

Android Dynamic Layout

Android has given wonderful method of developing xml based user interface, which at times can be as easy as drag and drop but in case where the developer is not aware of any particular element's requirement in advance layout must be developed on the fly dynamically. For example let us assume that the number of EditTexts required in the layout is not known in advance and that will be decide by the user then that has to be created dynamically.

With this small tutorial the learning objectives can be as follows

1. Declaring and using the linear layout and other components through the code.

LinearLayout linearLayout = new LinearLayout(this);
In this project we are not using xml based UI. Se we have to declare the linear layout in the manner depicted above and then setting the relevant parameters as given in the code attached with this post.

2. Generating multiple EditTexts dynamically.

final EditText editTextArray[] = new EditText[4];

Declaring and array of EditTexts of size 4 because we want to generate 4 EditTexts. We are using a fixed array but this can be replaced by dynamic array as well. When generating any component dynamically its id will not be seen in so please don't worry about that.

for (int i = 0; i < editTextArray.length; i++) {
textView1=new TextView(this);
editTextArray[i] = new EditText(this);


This particular piece of code generates EditTexts dynamically, it also sets the input type as number decimal and then adding them to a particular row.

3. Generating TextView dynamically and setting their properties such has text size, color etc.


Text view's all the properties can be set through the code itself as it can be seen the size of texts and the color of text is set through the code. For setting color two ways are available one is passing the int id of the color and the second method is using the in build color class.

4. Extracting the values from dynamically generated EditTexts.

for (int i = 0; i < editTextArray.length; i++){
// i am doing nothing in case of blank input

This particular piece of code is responsible for extracting the data from the dynamically generated EditTexts. I am using equals method to check whether the EditText is blank or not in case of blank i am doing nothing you can give a message to the user that EditText can not be blank or whatever you feel is better.

5. Setting the number type decimal through the code.


This is how input type can be set from the code itself, in this case we are setting it as a number decimal, it can be set to anything eg. number, phone, decimal etc.

No comments:

Post a Comment