Android RecyclerView Example

RecyclerView can be used to implement ListView, GridView, and Staggered GridView. It is more powerful because it is just like a framework, you can use your preferred layout manager to lay out the data in RecyclerView. And specify the scroll orientation as you like. It is highly decoupling and flexible.

1. Steps To Use RecyclerView.

  1. If your android SDK version is low, you need to add the RecyclerView library ( below code ) in your android project build.gradle file like below.
    compile 'com.android.support:recyclerview-v7:24.2.1'
  2. Add the RecyclerView widget in a layout XML file.
  3. Use findViewById() method to get the RecyclerView instance.
  4. Set RecyclerView layout manager.
  5. Set RecyclerView data adapter.
  6. Set RecyclerView item divider if you required.

2. RecyclerView Implement ListView Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/CiJqemaqjDo

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/AnCzl469wqw

  1. Below is the source code that implements the above effects.
    // Get the RecyclerView object.
     RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerViewExample);
     
     // Create an LinearLayoutManager object.
     LinearLayoutManager layoutManager = new LinearLayoutManager(this);
     layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
     //layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
     // Use LinearLayout to layout the item in RecyclerView.
     recyclerView.setLayoutManager(layoutManager); 
     
     // Create a new RecyclerView Adapter.
     recyclerViewAdapter = new RecyclerViewAdapter(this.initRecyclerViewItemDtoList(layout));
    
    // Set the data adapter to RecyclerView object.
     recyclerView.setAdapter(recyclerViewAdapter);
     
     // Use default linear layout item divider.
     DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getApplicationContext(), orientation);
     recyclerView.addItemDecoration(dividerItemDecoration);

3. RecyclerView Implement GridView Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/ZNbwbDbLMrk

  1. Below is the source code that implements the above video example.
    // Get the RecyclerView object.
     RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerViewExample);
     
     // Create a GridLayoutManager object.
     GridLayoutManager layoutManager = new GridLayoutManager(this, 5);
     recyclerView.setLayoutManager(layoutManager); 
     
     // Create a new RecyclerView Adapter.
     recyclerViewAdapter = new RecyclerViewAdapter(this.initRecyclerViewItemDtoList(layout));
    
    // Set the data adapter to RecyclerView object.
     recyclerView.setAdapter(recyclerViewAdapter);
     
     // Use gird or staggered grid layout item divider.
     RecyclerViewDividerGrid gridItemDivider = new RecyclerViewDividerGrid(getApplicationContext());
     recyclerView.addItemDecoration(gridItemDivider);

4. RecyclerView Implement StaggeredGridView Example.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/s0UN0e2HoYA

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/YtJce_PXFnM

  1. The below source code can implement the above example.
    // Get the RecyclerView object.
     RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerViewExample);
     
     // Create a StaggeredGridLayoutManager object.
     StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, orientation);
     recyclerView.setLayoutManager(layoutManager); 
     
     // Create a new RecyclerView Adapter.
     recyclerViewAdapter = new RecyclerViewAdapter(this.initRecyclerViewItemDtoList(layout));
    
    // Set the data adapter to RecyclerView object.
     recyclerView.setAdapter(recyclerViewAdapter);
     
     // Use gird or staggered grid layout item divider.
     RecyclerViewDividerGrid gridItemDivider = new RecyclerViewDividerGrid(getApplicationContext());
     recyclerView.addItemDecoration(gridItemDivider);

5. Main Layout XML File.

  1. activity_recycler_view.xml
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerViewExample"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

6. RecyclerView Item Layout Xml File.

  1. activity_recycler_view_item.xml
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp">
    
        <ImageView
            android:id="@+id/recyclerViewItemImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
        <TextView
            android:id="@+id/recyclerViewItemText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20dp"/>
    
    </LinearLayout>

7. Main Activity Java File.

  1. This is the launcher activity java file.
  2. RecyclerViewActivity.java
    package com.dev2qa.example;
    
    import android.os.Bundle;
    import android.support.v7.app.ActionBar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.DividerItemDecoration;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.StaggeredGridLayoutManager;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class RecyclerViewActivity extends AppCompatActivity {
    
        ActionBar actionBar = null;
    
        private final int RECYCLER_VIEW_LINEAR_LAYOUT = 1;
    
        private final int RECYCLER_VIEW_GRID_LAYOUT = 2;
    
        private final int RECYCLER_VIEW_STAGGERED_GRID_LAYOUT = 3;
    
        RecyclerViewAdapter recyclerViewAdapter = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_recycler_view);
    
            // Get ActionBar
            actionBar = getSupportActionBar();
            // Show action bar logo.
            actionBar.setDisplayShowHomeEnabled(true);
            actionBar.setDisplayUseLogoEnabled(true);
            // Set action bar logo.
            actionBar.setLogo(R.drawable.icon_tech_32);
            // Set action bar title.
            actionBar.setTitle("dev2qa.com - RecyclerView Example");
    
            // Get the RecyclerView object.
            RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerViewExample);
    
            //int layout = this.RECYCLER_VIEW_LINEAR_LAYOUT;
            //int layout = this.RECYCLER_VIEW_GRID_LAYOUT;
            int layout = this.RECYCLER_VIEW_STAGGERED_GRID_LAYOUT;
    
            //int orientation = LinearLayout.VERTICAL;
            //int orientation = LinearLayout.HORIZONTAL;
            //int orientation = StaggeredGridLayoutManager.VERTICAL;
            int orientation = StaggeredGridLayoutManager.HORIZONTAL;
    
            this.setRecyclerViewLayoutManager(recyclerView, layout, orientation);
    
            this.setRecyclerViewDataAdapter(recyclerView, layout);
    
            this.setRecyclerViewItemDivider(recyclerView, layout, true, orientation);
        }
    
        // Set recycler view layout manager.
        private void setRecyclerViewLayoutManager(RecyclerView recyclerView, int layout, int orientation)
        {
            if(layout == RECYCLER_VIEW_GRID_LAYOUT)
            {
                // Create a GridLayoutManager object.
                GridLayoutManager layoutManager = new GridLayoutManager(this, 5);
                recyclerView.setLayoutManager(layoutManager);
            }else if(layout == RECYCLER_VIEW_STAGGERED_GRID_LAYOUT)
            {
                // Create a StaggeredGridLayoutManager object.
                StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, orientation);
                recyclerView.setLayoutManager(layoutManager);
            }else
            {
                // Default use linear layout manager.
                // Create an LinearLayoutManager object.
                LinearLayoutManager layoutManager = new LinearLayoutManager(this);
                layoutManager.setOrientation(orientation);
                //layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                // Use LinearLayout to layout the item in RecyclerView.
                recyclerView.setLayoutManager(layoutManager);
            }
        }
    
        // Set recycler view data adapter.
        private void setRecyclerViewDataAdapter(RecyclerView recyclerView, int layout)
        {
            // Create a new RecyclerView Adapter.
            recyclerViewAdapter = new RecyclerViewAdapter(this.initRecyclerViewItemDtoList(layout));
    
            // Set the data adapter to RecyclerView object.
            recyclerView.setAdapter(recyclerViewAdapter);
        }
    
        // Set recycler view item divider.
        private void setRecyclerViewItemDivider(RecyclerView recyclerView, int layout, boolean useDefault, int orientation)
        {
            // Add RecyclerView item divider.
    
            if(layout == RECYCLER_VIEW_LINEAR_LAYOUT)
            {
                if(useDefault)
                {
                    // Use default linear layout item divider.
                    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getApplicationContext(), orientation);
                    recyclerView.addItemDecoration(dividerItemDecoration);
                }else
                {
                    // Use custom linear layout item divider.
                    RecyclerViewDividerLinear linearItemDivider = new RecyclerViewDividerLinear(this, orientation);
                    recyclerView.addItemDecoration(linearItemDivider);
                }
            }else
            {
                // Use gird or staggered grid layout item divider.
                RecyclerViewDividerGrid gridItemDivider = new RecyclerViewDividerGrid(getApplicationContext());
                recyclerView.addItemDecoration(gridItemDivider);
            }
        }
    
        private List<RecyclerViewItemDTO> initRecyclerViewItemDtoList(int layout)
        {
            List<RecyclerViewItemDTO> ret = new ArrayList<RecyclerViewItemDTO>();
    
            for(int i=0;i<20;i++)
            {
                RecyclerViewItemDTO itemDto = new RecyclerViewItemDTO();
                if(i%2 == 0) {
                    if(layout != RECYCLER_VIEW_STAGGERED_GRID_LAYOUT) {
                        itemDto.setImageId(R.drawable.smile_face_icon_72_72);
                        //itemDto.setImageId(R.drawable.smile_face_256_256);
                        itemDto.setTitle("Smile Face");
                    }else
                    {
                        itemDto.setImageId(R.drawable.beautiful_girl_1);
                    }
                }else
                {
                    if(layout != RECYCLER_VIEW_STAGGERED_GRID_LAYOUT) {
                        itemDto.setImageId(R.drawable.apple_icon_72_72);
                        //itemDto.setImageId(R.drawable.red_apple_256_256);
                        itemDto.setTitle("Red Apple");
                    }else
                    {
                        itemDto.setImageId(R.drawable.beautiful_girl_2);
                    }
                }
                ret.add(itemDto);
            }
    
            return ret;
        }
    
        // This method is used to inflate the add delete menu for action bar.
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Get menu inflater..
            MenuInflater menuInflater = getMenuInflater();
            // Inflate the add delete action menu.
            menuInflater.inflate(R.menu.action_bar_add_delete_example, menu);
            return super.onCreateOptionsMenu(menu);
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int itemId = item.getItemId();
            if(itemId == R.id.menuAdd)
            {
                this.recyclerViewAdapter.addItem(1);
            }else if(itemId == R.id.menuDelete)
            {
                this.recyclerViewAdapter.removeItem(1);
            }
            return super.onOptionsItemSelected(item);
        }
    }

8. RecyclerView Data Adapter Java File.

  1. RecyclerViewAdapter.java
    package com.dev2qa.example;
    
    import android.support.v7.widget.RecyclerView;
    import android.view.Display;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.view.ViewGroup.LayoutParams;
    import android.widget.ImageView;
    import android.widget.Toast;
    
    import java.util.List;
    import java.util.Random;
    
    public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
    
        private List<RecyclerViewItemDTO> itemDTOList;
    
        private int screenWidth = 0;
    
        public RecyclerViewAdapter(List<RecyclerViewItemDTO> itemDTOList) {
            this.itemDTOList = itemDTOList;
        }
    
        // This method is called to create and return the ViewHolder object.
        @Override
        public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            // Get LayoutInflater object.
            LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
            // Inflate the RecyclerView item layout xml.
            View itemView = layoutInflater.inflate(R.layout.activity_recycler_view_item, parent, false);
    
            // For StaggeredGridLayout, change the itemView width and height.
            this.randomChangeItemViewSize(parent, itemView);
    
            // Add on click listener to the item view.
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(view.getContext(), "You clicked RecyclerView item.", Toast.LENGTH_SHORT).show();
                }
            });
    
            // Add on click listener to the item view's child image view.
            ImageView itemImageView = (ImageView)itemView.findViewById(R.id.recyclerViewItemImage);
            itemImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(view.getContext(), "You clicked ImageView in RecyclerView item.", Toast.LENGTH_SHORT).show();
                }
            });
    
            // Create and return our custom RecyclerViewHolder object.
            RecyclerViewHolder ret = new RecyclerViewHolder(itemView);
            return ret;
        }
    
        // Change the itemView width and height randomly,
        // Only used for staggered grid layout.
        private void randomChangeItemViewSize(ViewGroup parent, View itemView)
        {
            // Get a random height.
            Random random = new Random();
            int randomHeight = random.nextInt(300);
    
            LayoutParams layoutParams = itemView.getLayoutParams();
            layoutParams.height = 300 + randomHeight;
    
            if(screenWidth==0)
            {
                Display display = parent.getDisplay();
                screenWidth = display.getWidth();
            }
    
            // Because our staggered grid layout example has three column
            // So each column occupy one third of the screen width.
            layoutParams.width = screenWidth / 3;
    
            itemView.setLayoutParams(layoutParams);
        }
    
        @Override
        public void onBindViewHolder(RecyclerViewHolder holder, int position) {
            // Get item dto in list.
            RecyclerViewItemDTO itemDto = itemDTOList.get(position);
            // Set item image resource id.
            holder.getItemImageView().setImageResource(itemDto.getImageId());
            // Set item text.
            holder.getItemTextView().setText(itemDto.getTitle());
        }
    
        // Return the data list count that will be displayed in RecyclerView.
        @Override
        public int getItemCount() {
            int ret = 0;
            if(this.itemDTOList!=null)
            {
                ret = this.itemDTOList.size();
            }
            return ret;
        }
    
        public void addItem(int position) {
            // Create and add a new menu item.
            RecyclerViewItemDTO newItemDto = new RecyclerViewItemDTO();
            newItemDto.setImageId(R.drawable.apple_icon_72_72);
            newItemDto.setTitle("Red Apple");
            this.itemDTOList.add(position, newItemDto);
    
            // Notify RecyclerView the add item event.
            notifyItemInserted(position);
        }
    
        public void removeItem(int position) {
            // Remove item from the list.
            this.itemDTOList.remove(position);
            // Notify RecyclerView the remove item event.
            notifyItemRemoved(position);
        }
    }

9. RecyclerView Holder Java File.

  1. This class is used to hold and cache RecyclerView item view objects.
  2. RecyclerViewHolder.java
    package com.dev2qa.example;
    
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    // This class is used to store RecyclerView child view objects for one row.
    // It's purpose is to improve RecyclerView performance.
    public class RecyclerViewHolder extends RecyclerView.ViewHolder {
    
        // Cache the RecyclerView item image object.
        private ImageView itemImageView = null;
        // Cache the RecyclerView item text object.
        private TextView itemTextView = null;
    
    
        public RecyclerViewHolder(View itemView) {
            super(itemView);
            if(itemView!=null) {
                itemImageView = itemView.findViewById(R.id.recyclerViewItemImage);
                itemTextView = itemView.findViewById(R.id.recyclerViewItemText);
            }
        }
    
        public ImageView getItemImageView() {
            return itemImageView;
        }
    
        public TextView getItemTextView() {
            return itemTextView;
        }
    }

10. RecyclerView Item Data DTO.

  1. RecyclerViewItemDTO.java
    package com.dev2qa.example;
    
    // This class stores item data for RecyclerView.
    public class RecyclerViewItemDTO {
    
        private String title = "";
    
        private int imageId = 0;
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public int getImageId() {
            return imageId;
        }
    
        public void setImageId(int imageId) {
            this.imageId = imageId;
        }
    }

11. RecyclerView Custom LinearLayout Item Divider.

  1. RecyclerViewDividerLinear.java
    package com.dev2qa.example;
    
    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Rect;
    import android.graphics.drawable.Drawable;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    
    public class RecyclerViewDividerLinear extends RecyclerView.ItemDecoration {
    
        // Used to draw item split line.
        protected Drawable itemDividerDrawable;
    
        // Item split line orientation.
        protected int itemDividerOrientation;
    
        public RecyclerViewDividerLinear(Context ctx, int orientation) {
            itemDividerDrawable = ctx.getDrawable(R.drawable.custom_recycler_view_divider_background);
            setOrientation(orientation);
        }
    
        public void setOrientation(int orientation) {
            if (orientation != LinearLayoutManager.HORIZONTAL && orientation != LinearLayoutManager.VERTICAL) {
                throw new IllegalArgumentException("invalid orientation");
            }
            itemDividerOrientation = orientation;
        }
    
        @Override
        public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
            if (itemDividerOrientation == LinearLayoutManager.VERTICAL) {
                drawVertical(canvas, parent);
            } else {
                drawHorizontal(canvas, parent);
            }
        }
    
        public void drawVertical(Canvas canvas, RecyclerView parent) {
            int leftPoint = parent.getPaddingLeft();
            int rightPoint = parent.getWidth() - parent.getPaddingRight();
    
            int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++) {
                View child = parent.getChildAt(i);
                //android.support.v7.widget.RecyclerView v = new android.support.v7.widget.RecyclerView(parent.getContext());
                RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
    
                int topPoint = child.getBottom() + layoutParams.bottomMargin;
                int bottomPoint = topPoint + itemDividerDrawable.getIntrinsicHeight();
    
                itemDividerDrawable.setBounds(leftPoint, topPoint, rightPoint, bottomPoint);
                itemDividerDrawable.draw(canvas);
            }
        }
    
        public void drawHorizontal(Canvas canvas, RecyclerView parent) {
            int topPoint = parent.getPaddingTop();
            int bottomPoint = parent.getHeight() - parent.getPaddingBottom();
    
            int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++) {
                View child = parent.getChildAt(i);
                RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
    
                int leftPoint = child.getRight() + layoutParams.rightMargin;
                int rightPoint = leftPoint + itemDividerDrawable.getIntrinsicHeight();
    
                itemDividerDrawable.setBounds(leftPoint, topPoint, rightPoint, bottomPoint);
                itemDividerDrawable.draw(canvas);
            }
        }
    
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            if (this.itemDividerOrientation == LinearLayoutManager.VERTICAL) {
                outRect.set(0, 0, 0, this.itemDividerDrawable.getIntrinsicHeight());
            } else {
                outRect.set(0, 0, this.itemDividerDrawable.getIntrinsicWidth(), 0);
            }
        }
    }

12. RecyclerView Custom GridLayout Item Divider.

  1. RecyclerViewDividerGrid.java
    package com.dev2qa.example;
    
    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Rect;
    import android.graphics.drawable.Drawable;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.RecyclerView.LayoutManager;
    import android.support.v7.widget.StaggeredGridLayoutManager;
    import android.view.View;
    
    public class RecyclerViewDividerGrid extends RecyclerView.ItemDecoration {
    
        // Used to draw item split line.
        protected Drawable itemDividerDrawable;
    
        public RecyclerViewDividerGrid(Context ctx) {
            itemDividerDrawable = ctx.getDrawable(R.drawable.custom_recycler_view_divider_background);
        }
    
        @Override
        public void onDraw(Canvas canvas, RecyclerView parent, RecyclerView.State state) {
            drawHorizontal(canvas, parent);
            drawVertical(canvas, parent);
        }
    
        // Get grid column count.
        private int getColumnCount(RecyclerView parent)
        {
            int columnCount = -1;
    
            // Get RecyclerView layout manager.
            LayoutManager layoutManager = parent.getLayoutManager();
    
            // If RecyclerView use GridLayoutManager.
            if (layoutManager instanceof GridLayoutManager)
            {
                columnCount = ((GridLayoutManager) layoutManager).getSpanCount();
            }
            // If RecyclerView use StaggeredGridLayoutManager.
            else if (layoutManager instanceof StaggeredGridLayoutManager)
            {
                columnCount = ((StaggeredGridLayoutManager) layoutManager).getSpanCount();
            }
            return columnCount;
        }
    
        public void drawHorizontal(Canvas canvas, RecyclerView parent)
        {
            int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++)
            {
                View child = parent.getChildAt(i);
                RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
    
                int top = child.getBottom() + layoutParams.bottomMargin;
                int bottom = top + this.itemDividerDrawable.getIntrinsicHeight();
    
                int left = child.getLeft() - layoutParams.leftMargin;
                int right = child.getRight() + layoutParams.rightMargin + this.itemDividerDrawable.getIntrinsicWidth();
    
                this.itemDividerDrawable.setBounds(left, top, right, bottom);
                this.itemDividerDrawable.draw(canvas);
            }
        }
    
        public void drawVertical(Canvas canvas, RecyclerView parent)
        {
            int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++)
            {
                View child = parent.getChildAt(i);
    
                RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
    
                int top = child.getTop() - layoutParams.topMargin;
                int bottom = child.getBottom() + layoutParams.bottomMargin;
    
                int left = child.getRight() + layoutParams.rightMargin;
                int right = left + this.itemDividerDrawable.getIntrinsicWidth();
    
                this.itemDividerDrawable.setBounds(left, top, right, bottom);
                this.itemDividerDrawable.draw(canvas);
            }
        }
    
        @Override
        public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
            int columnCount = getColumnCount(parent);
            int childCount = parent.getAdapter().getItemCount();
    
            // Do not need to draw bottom horizontal divider for the last row.
            if (isLastRaw(parent, itemPosition, columnCount, childCount))
            {
                outRect.set(0, 0, this.itemDividerDrawable.getIntrinsicWidth(), 0);
            }
            // Do not need to draw right vertical divider for the last column.
            else if (isLastColumn(parent, itemPosition, columnCount, childCount))
            {
                outRect.set(0, 0, 0, this.itemDividerDrawable.getIntrinsicHeight());
            } else
            {
                outRect.set(0, 0, this.itemDividerDrawable.getIntrinsicWidth(), this.itemDividerDrawable.getIntrinsicHeight());
            }
        }
    
        // Check whether this is the last row.
        private boolean isLastRaw(RecyclerView parent, int position, int columnCount, int childCount)
        {
            boolean ret = false;
    
            LayoutManager layoutManager = parent.getLayoutManager();
    
            // If RecyclerView use GridLayoutManager.
            if (layoutManager instanceof GridLayoutManager)
            {
                // Get the integral multiple times of columnCount value
                childCount = childCount - childCount % columnCount;
                // The last row item position bigger than or equal to integral multiple times of columnCount value.
                if (position >= childCount) {
                    ret = true;
                }
            }
            // If RecyclerView use StaggeredGridLayoutManager.
            else if (layoutManager instanceof StaggeredGridLayoutManager)
            {
                // Get StaggeredGridLayoutManager scroll orientation.
                int orientation = ((StaggeredGridLayoutManager) layoutManager).getOrientation();
    
                // If vertical scroll.
                if (orientation == StaggeredGridLayoutManager.VERTICAL)
                {
                    // Get the integral multiple times of columnCount value
                    childCount = childCount - childCount % columnCount;
                    // The last row item position bigger than or equal to integral multiple times of columnCount value.
                    if (position >= childCount) {
                        ret = true;
                    }
                } else
                // If horizontal scroll.
                {
                    // This condition means the last row.
                    if ((position + 1) % columnCount == 0)
                    {
                        ret = true;
                    }
                }
            }
            return ret;
        }
    
        // Check whether this is the last column.
        private boolean isLastColumn(RecyclerView parent, int position, int columnCount, int childCount)
        {
            boolean ret = false;
    
            LayoutManager layoutManager = parent.getLayoutManager();
    
            // If RecyclerView use GridLayoutManager.
            if (layoutManager instanceof GridLayoutManager)
            {
                // This condition means the last column.
                if((position + 1) % columnCount == 0)
                {
                    ret = true;
                }
            }
            // If RecyclerView use StaggeredGridLayoutManager.
            else if (layoutManager instanceof StaggeredGridLayoutManager)
            {
                // Get scroll orientation
                int orientation = ((StaggeredGridLayoutManager) layoutManager).getOrientation();
                // If scroll vertical.
                if (orientation == StaggeredGridLayoutManager.VERTICAL)
                {
                    // This is the last column
                    if ((position + 1) % columnCount == 0)
                    {
                        ret = true;
                    }
                }
                // If scroll horizontal.
                else
                {
                    // The last column item position bigger than or equal to integral multiple times of columnCount value.
                    childCount = childCount - childCount % columnCount;
                    if (position >= childCount)
                        ret = true;
                }
            }
            return ret;
        }
    }
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Kristina Baldus

Thanks for this.

1
0
Would love your thoughts, please comment.x
()
x