Android 解决切换Tab后RecycleView/ListView自动回滚至顶部条目的Bug

未经本人授权,不得转载!否则必将维权到底

出了个 Bug,点击底部 Tab 切换 Fragment,Fragment 中的 RecycleView 自动回滚至第一个条目。正常情况应该是页面列表滚动到哪,再切换回 Tab 的时候还是在当前的滚动位置。

问题展示:

Bug复现.gif

尝试解决方案:

Debug 跟了一遍代码,发现代码里面并没有设置 RecycleView.smoothScrollToPosition() / ListView.setSelection() 这类的方法。查了很多也找不到头绪。后来无意中想到以前 ListView 抢焦点的 Bug,就尝试了一下,果不其然的解决了。

可行方案:

使用 descendantFocusability 属性解决:
API 描述如下:android:descendantFocusability
Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus.
Must be one of the following constant values.

该属性是当一个为 View 获取焦点时,定义 ViewGroup 和其子控件两者之间的关系。
属性的值有三种:
beforeDescendants:ViewGroup 会优先其子类控件而获取到焦点
afterDescendants:ViewGroup 只有当其子类控件不需要获取焦点时才获取焦点
blocksDescendants:ViewGroup 会覆盖子类控件而直接获得焦点

通常我们用到的是第三种,即在Item布局的根布局加上android:descendantFocusability=”blocksDescendants”的属性就解决了

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/content_bg"
    // 只需要加上这个属性,就解决了这个 Bug !!!
    android:descendantFocusability="blocksDescendants"
    android:orientation="vertical">

    <!-- tab-->
    <cn.keithxiaoy.PagerSlidingTabStrip
        android:id="@+id/keithxiaoySlidingTabStrip"
        android:layout_marginTop="?attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:layout_gravity="top"
        android:background="@android:color/white"
        android:textColor="@color/font_gray_dark"
        android:textSize="15sp"
        app:pstsIndicatorColor="@color/font_blue_light"
        app:pstsIndicatorHeight="2dp"
        app:pstsIndicatorMaxWidth="15dp"
        app:pstsShouldExpand="true"
        app:pstsTabPaddingLeftRight="10dp"
        app:pstsTextActiveColor="@color/font_blue"
        app:pstsUnderlineColor="#cccccc"
        app:pstsTextActiveSize="@dimen/font_size_large2"
        app:pstsUnderlineHeight="1px" />

    <!-- 加载的view-->
    <cn.keithxiaoy.LoadingDataTipsView
        android:id="@+id/keithxiaoyTipView"
        android:layout_below="@+id/keithxiaoySlidingTabStrip"
        android:visibility="gone"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </cn.keithxiaoy.LoadingDataTipsView>

    <!-- viewpager-->
    <cn.keithxiaoy.ViewPager
        android:id="@+id/keithxiaoyViewPager"
        android:layout_below="@+id/pagerSlidingTabStrip"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

解决后的效果展示:

Bug解决.gif

这 Bug 不常见,网上资料也不多,所以分享一下。希望能帮助到大家~


本文原创发布于微信公众号「keithxiaoy」,编程、思维、成长、正能量,关注并回复「编程」、「阅读」、「Java」、「Python」等关键字获取免费学习资料

不要给自己的人生设限

猜你喜欢

转载自blog.csdn.net/xiaoy_yan/article/details/81002211