Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fill RecyclerView with GridLayoutManager from right to left

I'm trying to fill some data into a RecyclerView with GridLayoutManager:

GridLayoutManager layoutManager = new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false); 

This will fill the data into the grid from left to right. The first item will be put into top-left place, etc.

But the app I'm developing is designed for an RTL language, so I need to make it fill from right to left.

I tried to change the last argument to true. But it just scrolled the RecyclerView all the way down.

Also setting layoutDirection attribute for RecyclerView doesn't work (without considering that my min API is 16 and this attribute is added for API17+):

<android.support.v7.widget.RecyclerView         android:id="@+id/grid"         android:layoutDirection="rtl"         android:layout_width="match_parent"         android:layout_height="match_parent"/> 

How can I create a right to left filled grid using RecyclerView?

like image 961
Ashkan Sarlak Avatar asked Oct 03 '15 09:10

Ashkan Sarlak


People also ask

How do I make staggered RecyclerView?

In order to use RecyclerView for creating staggering grid views, we need to use StaggeredGridLayoutManager. LayoutManager is responsible for measuring and positioning item views in the RecyclerView and also recycle the item views when they are no longer visible to the user.

How do you make the first item of RecyclerView of full width with a GridLayoutManager?

You just have to add spanSizeLookup command which will look at the desired position (in our case, it's 0, first pos) and set the span size of layout manager items in RecyclerView. All you need to take care is that the layout manager for your recyclerView should be GridLayoutManager. The rest of your code remains same.


2 Answers

Create a class that extends GridLayoutMAnager ,and override the isLayoutRTL() method like this:

public class RtlGridLayoutManager extends GridLayoutManager {      public RtlGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {         super(context, attrs, defStyleAttr, defStyleRes);     }      public RtlGridLayoutManager(Context context, int spanCount) {         super(context, spanCount);     }      public RtlGridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) {         super(context, spanCount, orientation, reverseLayout);     }      @Override     protected boolean isLayoutRTL(){         return true;     } } 
like image 62
Mohammad Ranjbar Z Avatar answered Oct 23 '22 13:10

Mohammad Ranjbar Z


The answer by Mohammad is true but you do not need to create a new class. you can simply override isLayoutRTL method.

GridLayoutManager lm = new GridLayoutManager(this, 2) {     @Override     protected boolean isLayoutRTL() {         return true;     } }; 
like image 24
Emad Razavi Avatar answered Oct 23 '22 13:10

Emad Razavi