当视图大小改变时ScrollView向下滚动

lum*_*umi 5 android scrollview

我目前有一个带有 LinearLayout 的 ScrollView 。我正在动态更改一些内容,例如动态设置长文本段落,并添加动态布局(按钮等)。这会导致线性布局的高度发生变化,从而导致 ScrollView 向下滚动。如何在布局动态更新时保持当前滚动位置?

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical
        android:gravity="center_horizontal"
        >

        <!-- Dynamic Content Here -->
    </LinearLayout>
</ScrollView>
Run Code Online (Sandbox Code Playgroud)

Pre*_*rem -1

我建议的一个选择是将滚动位置保存在包中并恢复它。

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putInt("xPos", scrollView.getScrollX());
    outState.putInt("yPos", scrollView.getScrollY());
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    int scrollX = savedInstanceState.getInt("xPos"); // Default value 0
    int scrollY = savedInstanceState.getInt("yPos");
    scrollView.scrollTo(scrollX, scrollY);
}
Run Code Online (Sandbox Code Playgroud)