1
votes

I have a linearlayout and have to inflate variable number of buttons at runtime in this Linearlayout. Now my problem is that when I give Orientation for this linear layout. if I give it Horizontal or Vertical which create the problem. Will explain it with example:-

Eg1: Input is 3 buttons

Expected Output: Button1 Button2 Button3 ( If all 3 fits in one line completely)

All the 3 buttons should be displayed in this linear layout and in same line(just like horizontal) provided they fit completely.

Eg2: Input is 4 Buttons and they cannot fit in whole line

Expected output:- Line1:- Button1 Button2 (Assuming Button3 is not fitting completely in this line)

             Line2:-  Button3 Button4

Currently if I set LinearLAyout's orientation as Horizontal then its forcing all the 4 buttons in one line and the UI is getting screwed up. Same is the case if I give orientation as vertical.

Can someone tell me how to handle this at run time so that only complete buttons are displayed in one line and it spreads over multiple lines. Some generic way to handle this case.

The layout can be considered something like this for static purpose:-

<LinearLayout
android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="horizontal">
   <Button
    android:id="@+id/button_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="YYYYYYYYYYYOOOOOOOOOOOOO"         
    android:textSize="75sp"/>
   <Button
    android:id="@+id/button_2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="AAAAAAFFFFFFFFFFGGGGGGGGG"         
    android:textSize="75sp"/>

 </LinearLayout>
2

2 Answers

1
votes

LinearLayout doesn't work that way. It will layout items either vertically or horizontally(It doesn't wrap). You have a few options.

It sounds like your buttons will be different sizes(so you probably don't want to use gridview), you can either create Vertical LinearLayout that houses several HorizontalLinearLayouts(that in turn hold the Button).

Alternatively you can roll your own custom ViewGroup. Both methods are going to require you to write the calculation logic for determining what fits on a row. Your custom view group will likely be cleaner in the end but require more knowledge about the View.

0
votes

what I understand is you need to load n number of views dynamically and you want your views to be auto carried over your parent view. I think what you need is just a gridview with a simple adapter. The "cell" of your gridview will be the buttons in your case. There is a lot of info out there about it. This is the simple guide provided from google.

http://developer.android.com/guide/topics/ui/layout/gridview.html

Hope I help you. Regards.