Search code examples
androidflowlayout

Android: Custom FlowLayout


I want to make this kind of menu of tags in android. Fill layout dynamically and align to center.
How can I do that?

Edited using library recommended by @Dory

<FlowLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:f="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    f:debugDraw="false"
    f:weightDefault="0"
    f:layoutDirection="ltr"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="6dip"
    android:paddingTop="6dip"
    android:paddingRight="12dip"
    android:paddingBottom="12dip"
    android:background="@android:color/black"
    android:id="@+id/l_flow"/>



   <Button xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginBottom="3dp"/>

Flowlayout in one xml file Button is in another xml file. I'm inflating Button then fLayout.addView(button);

what I get is this Padding top and bottom between views is higher than expected


Solution

  • finally I did it with help of this library. I have used only class FlowLayout and attr.xml My main.xml looks like this:

        <com.example.FlowTest.FlowLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/flow"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:background="@android:color/white"/>
    

    and my item layout looks like this:

    <Button xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"  
        android:layout_gravity="center_horizontal"
        android:padding="5dp"/>
    

    And in my Activity's onCreate method:

    LayoutInflater mInflater = LayoutInflater.from(this);
        mFlowLayout = (FlowLayout) findViewById(R.id.flow);
    
        String [] names = {"goods", "shops", "cars", "washing machine","blablabla","clothes","books"};
    
        for(int i = 0; i<names.length;i++){
            Button b = (Button)mInflater.inflate(R.layout.item_flow,mFlowLayout, false);
            b.setText(names[i]);
            mFlowLayout.addView(b);
        }