Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center items of a recyclerview?

I need to center elements in each row so they will be like in this mockup. I've been searching if there is any layout that works that way without look. items are centered in their rows.

mockup

This is how it looks now in my code.enter image description here

like image 817
Cristian Gomez Avatar asked May 02 '15 22:05

Cristian Gomez


2 Answers

Make recyclerview width to wrap_content and its container's layout_gravity to center_horizontal

 <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">

      <android.support.v7.widget.RecyclerView
           android:id="@+id/recycrer_view"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_gravity="center_horizontal"
           android:paddingLeft="16dp"
           android:paddingRight="16dp" />
 </LinearLayout>
like image 85
Ravi Yadav Avatar answered Oct 22 '22 14:10

Ravi Yadav


Take LinearLayout in your RecyclerView's item row layout then give android:layout_gravity="center" to LinearLayout.

For each row of images you have to take different LinearLayout.

Here is example code:

 <LinearLayout
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_gravity="center"
         android:orientation="horizontal">

            <ImageView
                android:id="@+id/image1"
                android:layout_width="64dp"
                android:layout_height="64dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:src="@drawable/image1" />

            <ImageView
                android:id="@+id/image2"
                android:layout_width="64dp"
                android:layout_height="64dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:src="@drawable/image2" />

           <ImageView
                android:id="@+id/image3"
                android:layout_width="64dp"
                android:layout_height="64dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:src="@drawable/image3" />

  </LinearLayout>
like image 41
Rajesh Avatar answered Oct 22 '22 13:10

Rajesh