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

时间:2014-12-31 19:22:56

标签: 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>

2 个答案:

答案 0 :(得分:0)

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

@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);
}

答案 1 :(得分:0)

我认为通过这些步骤你可以做到:

  • 创建从scrollview
  • 延伸的自定义滚动视图
  • 定义用于启用和禁用滚动的布尔属性
  • 检查onScollChanged方法的布尔变量,如果为真则返回false
  • 在将动态视图添加到容器
  • 之前,将布尔变量设置为true
  • 添加完成后将其设置为false

我希望这些可以帮助你