Skip to main content

Android Creating button dynamically and fill layout



I'm creating a button dynamically. The number of button is depend on the size of arraylist. the problem is, after creating the button I will add to the layout using addview method. The problem is I'm using linear layout, as by default orientation for linear layout is horizontal, so the button will fill the layout horizontally. Because of that some of the button is not visible. What I'm trying to achieve is something look like this





multiple button in android messaging contact





My code is like below:







Button[] tv = new Button[arraylist.size()];

for(int i=0;i<arraylist.size();i++){

tv[i] = new Button(getApplicationContext());

tv[i].setText(arraylist.get(i).toString());

tv[i].setTextColor(Color.parseColor("#000000"));

tv[i].setTextSize(20);

tv[i].setPadding(15, 5, 15, 5);

linearlayout.addView(tv[i]);

}







If I set the orientation of linear layout to vertical the button will fill vertically. So if there any solution to create the button dynamically and fill the layout both horizontal and vertical as shown by image.


Comments

  1. There is not a canned layout in the SDK that does exactly what you are aiming for (i.e. lay out as many children horizontally as will fit, then flow to the next line to lay out some more), so you will need to create a custom ViewGroup that accomplishes this purpose. Luckily for you, Romain Guy created one live on-screen during a presentation at Devoxx.

    Here is a link to that presentation video.

    Here is a link to the sample code and slides.

    HTH

    ReplyDelete
  2. use TableLayout instead of LinearLayout this is tutorial hope this will help you to get the idea

    ReplyDelete
  3. Does you set android:layout_width="fill_parent"?
    Do this if you don't.

    ReplyDelete
  4. Well, you can try using more sophisticated way. You can create horizontal linear layout, and add buttons to it. Every time you're attempting to add new button, you check if there is place for it, by finding difference between layout's and buttons widths.

    Each time your horizontal layout is filled, you add it to another vertical layout, and create another horizontal layout to store buttons left.

    I used that trick in my apps.

    ReplyDelete

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?