欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

安卓RecyclerView灵活适配:带“头”的RecyclerView

程序员文章站 2022-05-15 19:21:26
...
项目小模块功能实现的差不多了,近几日在做体验,其中有个页面使用了RecyclerView,并设有头布局独占两格!!!

像这样

安卓RecyclerView灵活适配:带“头”的RecyclerView

那么每个Item之间的空隙调节就回出现很大的问题,头布局两边距离屏幕的宽度显然和下边两列是不一样的当然,如果你还对头布局的设置存在一定问题,请参考:

https://blog.csdn.net/zxt0601/article/details/52267325

RecyclerView的万能适配器:https://www.cnblogs.com/liushilin/p/5720926.html(后续将给出详细的讲解),欢迎关注订阅博客https://blog.csdn.net/Sailor_luo

为RecyclerView添加Header和Footer:https://www.jianshu.com/p/991062d964cf


问题来了,到底如何适配这个页面呢?padding?margin?显然有点不太行

网上有一些解决方案是:

MyItemDecoration myItemDecoration = new MyItemDecoration(2, 60,true);

动态设置是对的,但是如何做到头和身体分开灵活控制呢?直接上工具吧!

import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class MyItemDecoration extends RecyclerView.ItemDecoration {

        private int spanCount;
        private int spacing;
        private boolean includeEdge;

        /**
         * 从哪个位置开始设置间距,有的宫格视图有头视图
         */
        private int startFrom;

        public MyItemDecoration(int spanCount, int spacing, boolean includeEdge) {
            this.spanCount = spanCount;
            this.spacing = spacing;
            this.includeEdge = includeEdge;
        }

        /**
         * 设置从哪个位置开始设置间距
         *
         * @param position
         */
        public void setStartFrom(int position) {
            this.startFrom = position;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int position = parent.getChildAdapterPosition(view); // item position
            if (position < startFrom) {
                return;
            }

            // position - startFrom排除不考虑的位置这样算才正确
            position = position - startFrom;
            int column = position % spanCount; // item column

            if (includeEdge) {
                outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
                outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)

                if (position < spanCount) { // top edge
                    outRect.top = spacing;
                }
                outRect.bottom = spacing; // item bottom
            } else {
                outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
                outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
                if (position >= spanCount) {
                    outRect.top = spacing; // item top
                }
            }
        }
    }
用法可想而知:

就调用他

public void setStartFrom(int position) {
            this.startFrom = position;
        }

问题解决!

相关标签: RecycleView

上一篇: dvwa(5)——File Inclusion

下一篇: 封装