RecycleView 分割线设置及监听滚动状态

一、RecycleView 分割线

ListView中的分割线可以通过属性divider和dividerHeight分别设置颜色值/图片及分割线高度。而RecycleView并没有提供这两个属性设置分割线。
作为ListView的升级版列表控件,当然也是支持分割线的设置的。RecycleView分割线需要通过addItemDecoration(ItemDecoration decor)设置;

ItemDecoration有3个方法,ItemDecoration并没有对其实现,需要我们自己实现自定义的分割线;
onDraw:其绘制将会在每个Item被绘制之前进行;
onDrawOver:在绘制完Item后进行绘制;
getItemOffsets:通过outRect.set()为每个item设置偏移量。

下面是网上提供的通用分割线实现类,可以根据自己不同需求做修改;

public class RecycleViewDivider extends RecyclerView.ItemDecoration {

    private Paint mPaint;
    private Drawable mDivider;
    private int mDividerHeight = 2;//分割线高度,默认为2px
    private int mOrientation;//列表的方向:LinearLayoutManager.VERTICAL或LinearLayoutManager.HORIZONTAL
    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};

    /**
     * 默认分割线:高度为2px,颜色为灰色
     *
     * @param context
     * @param orientation 列表方向
     */
    public RecycleViewDivider(Context context, int orientation) {
        if (orientation != LinearLayoutManager.VERTICAL && orientation != LinearLayoutManager
                .HORIZONTAL) {
            throw new IllegalArgumentException("请输入正确的参数!");
        }
        mOrientation = orientation;

        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
    }

    /**
     * 自定义分割线
     *
     * @param context
     * @param orientation 列表方向
     * @param drawableId  分割线图片,高度默认为图片原始高度
     */
    public RecycleViewDivider(Context context, int orientation, int drawableId) {
        this(context, orientation);
        mDivider = ContextCompat.getDrawable(context, drawableId);
        mDividerHeight = mDivider.getIntrinsicHeight();
    }

    /**
     * 自定义分割线
     *
     * @param context
     * @param orientation 列表方向
     * @param drawable    分割线图片,高度默认为图片原始高度
     */
    public RecycleViewDivider(Context context, int orientation, Drawable drawable) {
        this(context, orientation);
        mDivider = drawable;
        mDividerHeight = mDivider.getIntrinsicHeight();
    }

    /**
     * 自定义分割线
     *
     * @param context
     * @param orientation 列表方向
     * @param drawable    分割线图片
     * @param drawableHeight    分割线图片高度
     */
    public RecycleViewDivider(Context context, int orientation, Drawable drawable, int
            drawableHeight) {
        this(context, orientation);
        mDivider = drawable;
        mDividerHeight = drawableHeight;
    }

    /**
     * 自定义分割线
     *
     * @param context
     * @param orientation   列表方向
     * @param dividerHeight 分割线高度
     * @param dividerColor  分割线颜色
     */
    public RecycleViewDivider(Context context, int orientation, int dividerHeight, int
            dividerColor) {
        this(context, orientation);
        mDividerHeight = dividerHeight;
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(dividerColor);
        mPaint.setStyle(Paint.Style.FILL);
    }


    //获取分割线尺寸
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State
            state) {
        super.getItemOffsets(outRect, view, parent, state);
        outRect.set(0, 0, 0, mDividerHeight);
    }

    //绘制分割线
    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
        if (mOrientation == LinearLayoutManager.VERTICAL) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }
    }

    //绘制横向 item 分割线
    private void drawHorizontal(Canvas canvas, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getMeasuredWidth() - parent.getPaddingRight();
        final int childSize = parent.getChildCount();
        for (int i = 0; i < childSize; i++) {
            final View child = parent.getChildAt(i);
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getBottom() + layoutParams.bottomMargin;
            final int bottom = top + mDividerHeight;
            if (mDivider != null) {
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(canvas);
            }
            if (mPaint != null) {
                canvas.drawRect(left, top, right, bottom, mPaint);
            }
        }
    }

    //绘制纵向 item 分割线
    private void drawVertical(Canvas canvas, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getMeasuredHeight() - parent.getPaddingBottom();
        final int childSize = parent.getChildCount();
        for (int i = 0; i < childSize; i++) {
            final View child = parent.getChildAt(i);
            RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getRight() + layoutParams.rightMargin;
            final int right = left + mDividerHeight;
            if (mDivider != null) {
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(canvas);
            }
            if (mPaint != null) {
                canvas.drawRect(left, top, right, bottom, mPaint);
            }
        }
    }
}

这里设置横向图片分割线,分割线的高度默认为图片高度;

 mRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager
                .HORIZONTAL, R.mipmap.divier_img));

二、RecycleView 监听滚动状态、及顶部/末尾位置

还记得ListView是如何监听滚动到顶部或末尾的吗?通过设置setOnScrollListener实现的;

mListView.setOnScrollListener(new AbsListView.OnScrollListener() {

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // TODO Auto-generated method stub
        if (scrollState==OnScrollListener.SCROLL_STATE_IDLE) {
            // 滚动停止
        }else if (scrollState==OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
            // 手指滚动状态
        }else if (scrollState==OnScrollListener.SCROLL_STATE_FLING) {
            // 手指不动了,但是屏幕还在滚动状态,靠惯性滚动
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        // TODO Auto-generated method stub
        if (firstVisibleItem==0) {
            // 滚动到顶部
        }else if (firstVisibleItem+visibleItemCount>= totalItemCount) {
            // 滚动到尾部
        }
    }
});

在RecycleView中,可以通过线性布局对象LinearLayoutManager监听顶部/尾部位置;
其提供以下方法(主要区别是item是否完全显示,还是存在一半被遮挡);
findFirstVisibleItemPosition() :第一个显示的item位置;
findFirstCompletelyVisibleItemPosition() :第一个完全显示的item位置;
findLastVisibleItemPosition() :最后一个显示的item位置;
findLastCompletelyVisibleItemPosition():最后一个完全显示的item位置。

接着设置滚动监听setonScrollListener,然后对第一个显示的item位置和末尾显示的item位置判断是否滚动到屏幕开始/末尾。

mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            // TODO Auto-generated method stub
            if (!(mLayoutManager instanceof LinearLayoutManager)) {
                Toast.makeText(MainActivity.this, "不是线性的布局结构", Toast.LENGTH_SHORT).show();
                return;
            }
            LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mLayoutManager;
            if (linearLayoutManager.findFirstCompletelyVisibleItemPosition() == 0) {
                Toast.makeText(MainActivity.this, "滚动到顶部", Toast.LENGTH_SHORT).show();
            }
            if (linearLayoutManager.findLastCompletelyVisibleItemPosition() == mRecyclerView
                    .getAdapter().getItemCount() - 1) {
                Toast.makeText(MainActivity.this, "滚动到尾部", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            // TODO Auto-generated method stub
            if (newState==RecyclerView.SCROLL_STATE_IDLE){
                Toast.makeText(MainActivity.this, "滚动停止", Toast.LENGTH_SHORT).show();
            }else if (newState == RecyclerView.SCROLL_STATE_DRAGGING){
                Toast.makeText(MainActivity.this, "手指拖动", Toast.LENGTH_SHORT).show();
            }else if (newState==RecyclerView.SCROLL_STATE_SETTLING){
                Toast.makeText(MainActivity.this, "手指离开屏幕,滑动", Toast.LENGTH_SHORT).show();
            }
        }
    });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值