Search code examples
androidandroid-viewholdergridlayoutmanager

Change layout of GridLayoutManager


What I want to achieve:

enter image description here

What I did:

I have a button with 1 to 5 columns, when the user clic on the number of column he wants, the layout change but all the card are glued to each other. So far this is what I have been able to do: https://i.sstatic.net/OCzgW.jpg

My item:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/card"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/video_preview"
        android:layout_width="match_parent"
        android:layout_height="194dp"
        android:scaleType="centerCrop"
        tools:src="@drawable/img_error_v1"
        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp">
        <TextView
            android:id="@+id/video_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?attr/textAppearanceHeadline6"
            android:maxLines="1"
            tools:text="This is a really really really really really really really really really really really long title"
            />
        <TextView
            android:id="@+id/video_description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:maxLines="1"
            android:textAppearance="?attr/textAppearanceBody2"
            android:textColor="?android:attr/textColorSecondary"
            tools:text="This is the URL for now"
            />
    </LinearLayout>
</LinearLayout>

My question:

How can I achieve this kind of change ? I have read about ItemDecoration but I don't think I can change the layout_height of my item. Do I need create one layout for each column screen ?


Solution

  • I don't know if it is the right solution but this article help me change the layout of my view depending on the number of column.

    • The downside is that I need to create a different layout for each column layout I want to display.
    • The upside is that I have more control over the item of each of my layout and I can modify the text size or anything else.

    As it is a bit long I've created a repo to show how I've done it.

    There might be some improvement to make any help is appreciated :)