Search code examples
androidandroid-recyclerviewandroid-viewholder

How to Fit Recyler view items according to layout size in Android


I am using recycler to show 8 items in the list. However the number 8 is fixed. I want to resize the items according to the size of the parent layout in which recycler view is given. That means all 8 items should show in equal size and should fit into one screen view. No scrolling to be needed.

An Image for reference I have attached. RecyclerView

My question is how can I achieve this ?


Solution

  • Here maybe can be your reference, you can use RecyclerView with GridLayoutManager as your layoutManager and set your spanCount to 8 for making a grid with 8 items

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.recyclerview.widget.RecyclerView 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:spanCount="8"
        tools:listitem="@layout/item_recycler"
        tools:itemCount="8"/>
    

    In your item view just make sure everything in your layout is match with the parent like this

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    
        <View
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_margin="4dp"
            android:background="@color/black"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintDimensionRatio="1:1"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    Here is the result for the item layout

    enter image description here

    And this is the result that you expected, you also can validate your view using Layout Validation to make sure it is expected in any kind of size devices you want

    enter image description here