保存NestedScrollView的滚动状态

Jul*_*nma 5 android savestate android-nestedscrollview

我的应用程序围绕一个HomeActivity,底部包含4个选项卡.这些选项卡中的每一个都是一个片段,所有这些片段都是从头开始添加(不替换),并且在点击相应的选项卡时隐藏/显示它们.

我的问题是每当我更改标签时,我的滚动状态都会丢失.展示该问题的每个片段使用a android.support.v4.widget.NestedScrollView(参见下面的示例).

注意:使用RecyclerView或ListView的片段由于某种原因保持其滚动状态.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/include_appbar_title" />

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- Content -->

    </android.support.v4.widget.NestedScrollView>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

我读了几篇关于保存实例状态的帖子(这个,例如那个),他们的解决方案要么在我的场景中不起作用,要么实际上不实用,因为我有4-12个不同的片段我需要修改使其工作.

使嵌套滚动视图在片段更改时保持滚动位置的最佳方法是什么?

Jul*_*nma 15

我在onheeseesefactory上找到的一个解决方案是,默认情况下,片段的状态已保存(从EditText中的输入到滚动位置),但只有在给xml元素的ID时才会这样.

在我的例子中,只需在我的NestedScrollView中添加一个ID就可以解决问题:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/include_appbar_title" />

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/NestedScrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- Content -->

    </android.support.v4.widget.NestedScrollView>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

  • 你救了我的夜晚:) (2认同)
  • 你好,它可以与“导航组件”一起使用吗?因为我试过了但是没用,布局总是回到顶部 (2认同)
  • 它确实适用于导航组件 2.4.0 (2认同)