Search code examples
androidandroid-recyclerviewandroid-gridlayoutgridlayoutmanager

Android Grid Layout Manager not centering elements


I have the following recycler view inside a Constraint Layout (very simple)

<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".activities.PokemonFavoritesActivity"
tools:showIn="@layout/activity_pokemon_favorites">

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/rv_pokemon_favorites"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="2dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

enter image description here

And here is the method where I initialize the Recycler View:

  private void initializeRecyclerViewComponents() {
    favoritesRecyclerView = findViewById(R.id.rv_pokemon_favorites);
    layoutManager = new GridLayoutManager(this, 4);
    favoritesRecyclerView.setLayoutManager(layoutManager);
    pokemonFavoritesAdapter = new PokemonFavoritesAdapter(this, favoritePokemon);
    pokemonFavoritesAdapter.setClickListener(this);
    favoritesRecyclerView.setAdapter(pokemonFavoritesAdapter);
}

And here is the item_layout:

<?xml version="1.0" encoding="utf-8"?>
<com.mikhaellopez.circularimageview.CircularImageView 
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/civ_pokemon_favorite"
 android:layout_width="100dp"
 android:layout_height="100dp" />

However , as you can see in the image , the view is not "centered" (there is a lot of extra margin at the end of each row in comparison to the start) How can I do to center the 4 columns in order to have the same start and end spacing ?


Solution

  • Try wrapping your item view in a linearlayout and center the image in this. That should fix it.