美文网首页
RecyclerView添加ItemDecoration

RecyclerView添加ItemDecoration

作者: jacky123 | 来源:发表于2016-10-03 18:31 被阅读546次

    前言

    本来来自于项目:
    https://github.com/yqritc/RecyclerView-FlexibleDivider
    只需要简单的几句话就能设置我们想要的效果!


    具体的用法参照原项目!
    效果:


    RecyclerView 横向纵向间距设置

    Looking for custom ItemDecoration to achieve equal column space for GridLayoutManager?
    ItemOffsetDecoration:

    public class ItemOffsetDecoration extends RecyclerView.ItemDecoration {
    
        private int mItemOffset;
    
        public ItemOffsetDecoration(int itemOffset) {
            mItemOffset = itemOffset;
        }
    
        public ItemOffsetDecoration(@NonNull Context context, @DimenRes int itemOffsetId) {
            this(context.getResources().getDimensionPixelSize(itemOffsetId));
        }
    
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.set(mItemOffset, mItemOffset, mItemOffset, mItemOffset);
        }
    }
    

    In your source code, add ItemOffsetDecoration to your recyclerview.
    Item offset value should be half size of the actual value you want to add as space between items.

    mRecyclerView.setLayoutManager(new GridLayoutManager(context, NUM_COLUMNS);
    ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(context, R.dimen.item_offset);
    mRecyclerView.addItemDecoration(itemDecoration);
    

    Also, set item offset value as padding for its recyclerview, and specify android:clipToPadding=false.

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview_grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:padding="@dimen/item_offset"/>
    

    DONE. You will get an equal spaces around items.

    相关文章

      网友评论

          本文标题:RecyclerView添加ItemDecoration

          本文链接:https://www.haomeiwen.com/subject/umwdyttx.html