Search code examples
androidandroid-layoutkotlinandroid-recyclerviewcardview

How to Center RecyclerView with GridLayout (spanCount = 2)?


So I'm experimenting with RecyclerView.

This is my activity_main...

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/activityMain_recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:spanCount="2"/>
</LinearLayout>

This is my MainActivity...

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        cardView()
    }

    private fun cardView() {
        val adapterReference = GroupAdapter<GroupieViewHolder>()
        activityMain_recyclerView.adapter = adapterReference
       // activityMain_recyclerView.layoutManager = GridLayoutManager(this, 2)

        adapterReference.add(CardViewGroup())
        adapterReference.add(CardViewGroup())
        adapterReference.add(CardViewGroup())
        adapterReference.add(CardViewGroup())
        adapterReference.add(CardViewGroup())
        adapterReference.add(CardViewGroup())
        adapterReference.add(CardViewGroup())
        adapterReference.add(CardViewGroup())
        adapterReference.add(CardViewGroup())

    }
}

class CardViewGroup() : Item<GroupieViewHolder>() {
    override fun getLayout(): Int {
        return R.layout.layout_card_view
    }

    override fun bind(viewHolder: GroupieViewHolder, position: Int) {
    }

}

It currently looks like this...

I was hoping to make it look like...


Solution

  • Solved this problem.

    steps to follow for best results in recyclerView experience

    • Make <CardView> as the parent for your layout, and set its dimensions as...

      layout_width="match_parent"

      layout_height="wrap_content"

      layout_margin="16dp" try and remove this after building it to see the difference.

    • Make <ConstraintLayout> as the container inside the <CardView> parent. and set its dimensions as...

      layout_width="match_parent"

      layout_height="wrap_content"

    P.s. Don't forget to add contrast to your Cardview background and recyclerView background to clearly see the difference