School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 307,012 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,039 people online right now. Registration is fast and FREE... Join Now!




Android, Part III: Dynamic Layouts

 
Reply to this topicStart new topic

> Android, Part III: Dynamic Layouts

gabehabe
Group Icon



post 7 Oct, 2009 - 10:38 AM
Post #1


Dynamic Layouts in Android
No XML in this tutorial! We'll be completely designing our application in Java, and creating our layout completely dynamically. The benefits of this are that we can add an undefined amount of widgets at run time. This is a pretty useful skill, but not brilliantly documented. (Everything is ZOMG LAYOUT.XML FTW!!1!)

We're only going to create a crude, eventless UI, but it's a good learning exercise:
Attached Image

Okay, so let's get started. We won't be touching on events in this tutorial, our app won't actually do anything, per se... it's merely an example of adding stuff dynamically. You'll notice how we set the properties through Java, quite similarly to how we define them in the XML.

To start off, remember we're creating a package, as usual.
Attached Image
CODE
package dreamincode.tutorials.dic_tut3;


Next, we're going to import the usual suspects... Activity and Bundle.
CODE
import android.app.Activity;
import android.os.Bundle;


The next two are new. One you may recognise from our layouts before... LinearLayout. We're also going to use a ScrollView. The reason we'll be using a ScrollView is that we're going to add a hell of a lot of widgets, and they wouldn't all fit on screen. If we don't put our LinearLayout inside a ScrollView, it simply won't scroll and the user won't be able to reach all the widgets!
CODE
import android.widget.ScrollView;
import android.widget.LinearLayout;


The last things we need to import are our widgets. We'll be using an EditText, a TextView, a Button and a CheckBox. We've already seen the first three in parts 1 and 2 of this tutorial, but the CheckBox is new. (And I hope the name is self-explanatory for what it is!) wink2.gif
CODE
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.CheckBox;


Now it's time to get on with our code. We're only going to extend Activity this time, remember we won't be using events. This bit's nothing new, so I'll just throw in the opening of the class and the opening of the onCreate() method. (Note, if you're not familiar with this, check part 1 and part 2)
CODE
public class dic_tut3 extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


Time to get dirty. Dynamic layouts aren't always the most elegant of solutions, but they can be fun, and sometimes easier to implement. They're also really useful for certain occasions (such as SmartCalc*, my app: it uses a dynamic layout to decide how many textboxes are needed at runtime)
* No link, it's a paid app and I don't want to look like an ad whore. smile.gif

Code first, explanation afterwards.
CODE
        ScrollView sv = new ScrollView(this);
        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        sv.addView(ll);

LINE 1: Creates a ScrollView object, which is a part of this Activity.
LINE 2: Creates a LinearLayout object, which you hopefully remember from the layout.xml we discussed before.
LINE 3: Sets the orientation of our LinearLayout. Remember how we used android:orientation="vertical" before? Same principal applies here.
LINE 4: Adds the LinearLayout to the ScrollView. Remember, we want to be able to Scroll the LinearLayout View.
NOTE: A ScrollView can **only** have one view added to it. If you try to add more than one, your application WILL force close. If you need to reset it, use ScrollView.removeAllViews(); and re-add whatever you need. (This is why we're going to add all our widgets to the LinearLayout as opposed to the ScrollView!)

Adding widgets dynamically
Actually, this same principal applies to all our widgets. But I'll use a few, just to demonstrate. smile.gif This one should look relatively familiar, since we played with TextView.setText() in part 2.
CODE
        TextView tv = new TextView(this);
        tv.setText("Dynamic layouts ftw!");
        ll.addView(tv);

Notice how we use addView() on ll, our LinearLayout, just like we added ll to sv? That's all it takes! smile.gif

Now, let's do a Button and a EditText. Same principal, just like I said:
CODE
        EditText et = new EditText(this);
        et.setText("weeeeeeeeeee~!");
        ll.addView(et);
        
        Button b = new Button(this);
        b.setText("I don't do anything, but I was added dynamically. :)");
        ll.addView(b);
(Remember, when you run the application, the button won't actually do anything: We haven't added an OnClickListener! If you want, you may want to revisit the button at the end of this tutorial and try adding an event by yourself. (Use part 2 of this series as a reference if you get stuck)

The next is still the same principal, but I've added it in a loop. 20 pointless CheckBoxes, coming up!
CODE
        for(int i = 0; i < 20; i++) {
            CheckBox cb = new CheckBox(this);
            cb.setText("I'm dynamic!");
            ll.addView(cb);
        }

This is really just to pad out our layout, so we can really see how useful that ScrollView is. smile.gif

The very last thing we need to do is use setContentView() -- similar to how we did before. Remember the this.setContentView(R.layout.main);? Pretty much the same, only now we're going to use the ScrollView we created earlier instead:
CODE
this.setContentView(sv);


And lastly, close off the method and class!
CODE
    }
}


Now, if you run this, you'll get a rather crude, but biiiig layout, complete with all the widgets that we added dynamically.

Complete code:
CODE
package dreamincode.tutorials.dic_tut3;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ScrollView;
import android.widget.LinearLayout;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.CheckBox;

public class dic_tut3 extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        ScrollView sv = new ScrollView(this);
        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        sv.addView(ll);
        
        TextView tv = new TextView(this);
        tv.setText("Dynamic layouts ftw!");
        ll.addView(tv);
        
        EditText et = new EditText(this);
        et.setText("weeeeeeeeeee~!");
        ll.addView(et);
        
        Button b = new Button(this);
        b.setText("I don't do anything, but I was added dynamically. :)");
        ll.addView(b);
        
        for(int i = 0; i < 20; i++) {
            CheckBox cb = new CheckBox(this);
            cb.setText("I'm dynamic!");
            ll.addView(cb);
        }
        this.setContentView(sv);
    }
}


See if you can add an OnClickListener to the button, just have a play about with it until you feel fairly confident... I won't be explaining too much about the layouts in the coming tutorials, more on actual features such as SQLite. smile.gif

Complete project: Attached File  dic_tut3.zip ( 25.83k ) Number of downloads: 45
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!


Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/21/09 07:20AM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month