实现GridLayoutManager支持RTL

在Android开发中,使用GridLayoutManager遇到在RTL(Right To Left)环境下,数据刷新时RecyclerView表现异常,每次添加数据或自动上滚一行。问题源于findReferenceChild方法。通过分析源码,发现在RTL模式下该方法获取的position不正确。为解决此问题,通过继承GridLayoutManager,重写findReferenceChild方法,在RTL模式下修正spanIndex的计算方式,从而修复了这一bug。
摘要由CSDN通过智能技术生成

最近在工作中遇见个奇怪现象,即RecyclerView 采用GridLayoutManager进行布局,当系统是LTR时,数据刷新时变现正常;但是如果是RTL情况下,每次数据添加或莫名其妙向上滚动一个单元格。测试提出这个问题后就开始疯狂找问题,最终定位是由于GridLayoutManager内部方法findReferenceChild引起的。

GridLayoutManager源码如下:

View findReferenceChild(RecyclerView.Recycler recycler, RecyclerView.State state,
                        int start, int end, int itemCount) {
    ensureLayoutState();
    View invalidMatch = null;
    View outOfBoundsMatch = null;
    final int boundsStart = mOrientationHelper.getStartAfterPadding();
    final int boundsEnd = mOrientationHelper.getEndAfterPadding();
    final int diff = end > start ? 1 : -1;
    for (int i = start; i != end; i += diff) {
        final View view = getChildAt(i);
        final int position = getPosition(view);
        if (position >= 0 && position < itemCount) {
            final int span = getSpanIndex(recycler, state, position);
            if (span != 0) {
                continue;
            }
            if (((RecyclerView.LayoutParams) view.getLayoutParams()).isItemRemoved()) {
                if (invalidMatch == null) {
                    invalidMatch = view; // removed item, least preferred
                }
            } else if (mOrientationHelper.getDecoratedStart(view) >= boundsEnd ||
                    mOrientationHelper.getDecoratedEnd(view) < boundsStart) {
                if (outOfBoundsMatch == null) {
                    outOfBoundsMatch = view; // item is not visible, less preferred
                }
            } else {
                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值