Tuesday, January 31, 2012

Programatically Adding Scrolling Multiple LinearLayouts In Android

 So, the other day I was working on a new App idea I have, and I was trying to learn how to add a dynamic number of LinearLayouts to an Activity that scrolled.  I couldn't find a really good example so after I finally pieced together how to do this, I decided I'd make a little tutorial.  This is my first blog EVER so here goes nothing.

First thing you will need to do, is create a ScrollView.  One thing you need to know about a ScrollView is that it can only have one main element.  So, you need to add a LinearLayout to the ScrollView, then all of your other LinearLayouts get added to that.  So, below is my code example on how to do this.  This will create 10 LinearLayouts with a button in each.  Also, at the end, I call setContentView(scrollView) instead of the default way an Activity is set up to use a layout Id.

public class DynamiclinearsActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScrollView scrollView= new ScrollView(this);
        LinearLayout mainLayout = new LinearLayout(this);
        mainLayout.setOrientation(LinearLayout.VERTICAL);               
        for (int i=0; i<10; i++){
            LinearLayout ll = new LinearLayout(this);
            ll.setOrientation(LinearLayout.HORIZONTAL);
            ll.setTag(i);                           
            TextView tv=new TextView(this);
            tv.setText("Row " + i);           
            ll.addView(tv);
            Button b = new Button(this);
            b.setTag(i);
            b.setText("Button " + i);           
            ll.addView(b);                   
            mainLayout.addView(ll);
        }
        scrollView.addView(mainLayout);
        setContentView(scrollView);
    }
}

The output looks like this...

2 comments:

  1. This post is written in a very good way and entails a lot of useful information for me. I am glad to find a good way of writing the post. Kindly also discuss with my website. Exit intent software


    ReplyDelete