Search code examples
androidandroid-recyclerviewwidthgridlayoutmanager

how to set width of each column of gridlayoutManager to wrapContent not fixed size in android


I user GridLayoutManager fro my recyclerView. I want to show my list like this image, but my output is different. I want to have a GridLayoutManager that each row has a different width depend on its width. my output

   binding.rcyHashtag.apply {
        layoutManager = GridLayoutManager(requireContext(), 3)
        adapter = simpleHashTagAdapter
    }

<LinearLayout
android:id="@+id/lay_root"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:focusable="true"
android:clickable="true"
android:background="@drawable/drw_bg_hashtag"
android:paddingEnd="2dp"
android:paddingStart="2dp"
android:layout_margin="2dp">
<TextView
    android:id="@+id/txt_title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/white"
    android:layout_gravity="center"
    android:gravity="center"
    android:textSize="12sp"
  />

desired


Solution

  • I have found the solution. I just used StaggeredGridLayoutManager for the recyclerView like this:

     binding.rcyHashtag.apply {
            layoutManager = StaggeredGridLayoutManager( 3,StaggeredGridLayoutManager.HORIZONTAL)
            adapter = simpleHashTagAdapter
        }