Sirwan Afifi
Sirwan Afifi

Reputation: 10824

android: Laying out items after each other

I'm generating some buttons via code:

LinearLayout layout = (LinearLayout) findViewById(R.id.layoutResult);
for (int i = 0; i < n; i++) {
    Button btn = new Button(MainActivity.this);
    btn.setText("Item " + i);
    btn.setId(i);
    layout.addView(btn);
}

Layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:id="@+id/layoutResult"
    android:orientation="horizontal">   
</LinearLayout>

That generates buttons and puts them on screen like below:

enter image description here

But my goal is that, laying out elements this way:

enter image description here

How can I achieve that using LinearLayout programmatically? Any idea?

Upvotes: 0

Views: 52

Answers (1)

reidisaki
reidisaki

Reputation: 1524

Have you taken a look at this? FlowLayout

http://nishantvnair.wordpress.com/2010/09/28/flowlayout-in-android/

Another way is to do it yourself in code, get the screen width, then you would figure out how many items can fit on the screen x-wise and calculate how many items can fit on a row before you need to add them to the next row.

Upvotes: 1

Related Questions