Search code examples
androidandroid-linearlayout

How to add an item in a new line in layout?


I am new at development in Android Studio. I want to add new boxes to the line below if the first row is full. In the image below, items #1,#2,#3,#4 are filling the whole width and so when I add a new item (box #5) it goes next to box #4. How can I add it to the second row automatically?

enter image description here

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:orientation="vertical"
        android:layout_margin="2dp"
        android:padding="1dp">

    <TextView
            android:id="@+id/text1"
            android:layout_width="wrap_content"
            android:layout_height="15dp"
            android:text="#test_hashtag"
            android:padding="5dp"
            android:gravity="center"
            android:background="@drawable/circle_text_bg"
            android:textColor="@android:color/black"
            android:textSize="13dp"/>

</LinearLayout>

circle_text_bg is drawing a border line on the boxes.

What I did try: I tried using a RecyclerView and a ListView instead of a TextView. But all of them go horizontally or vertically only.

Edit1: The items are dynamic. They are some hashtags (that means the first line might contain 3 items and the second might contain 4 items... etc.)


Solution

  • Consider using a RecyclerView with the GridLayoutManager.

    If you want four columns, you can do something like this:

    GridLayoutManager glm = new GridLayoutManager(context, 4);
    recyclerView.setLayoutManager(glm);
    

    Or, in XML:

    <RecyclerView
        ...
        app:spanCount="4"
        app:layoutManager="android.support.v7.widget.GridLayoutManager"
        />
    

    (androidx.recyclerview.widget.GridLayoutManager if you use AndroidX)