保持ScrollView滚动位置以获取动态内容

Men*_*ene 7 android scrollview

我想要存档的内容最好用图像来解释

在此输入图像描述

灰色框表示屏幕,蓝色框表示元信息,白色圆形框表示SearchView,红色框表示搜索返回的项目.

我到目前为止工作得很好,但是当用户搜索某些内容并且项目超出屏幕时会出现问题(1).然后用户向下滚动,因此元信息在屏幕外(2).用户现在仍然可以输入新的搜索查询,从而更改项目.但是,当新查询返回太少的项目来填充屏幕的其余部分时(3),ScrollView将"跳转"回到顶部(不在图像中,不需要).我想要的是SearchView保持放置的行为(3).一旦处于这种状态,用户就可以回滚到顶部(4).如果她这样做,她不能回滚,而是显示过度滚动指示.

在Google+应用中可以看到类似的行为.从开始屏幕转到您的个人资料(点击顶部的姓名).您将看到三个寄存器("关于我","帖子","照片"*).我有例如没有照片,行为如上所述.

编辑 ScrollView是视图的根.

编辑基本布局结构

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

  <LinearLayout
      android:orientation="vertical"
      android:layout_width="match_parent"
      android:layout_height="wrap_content">
      <View /> <!-- Meta info -->
      <SearchView />
      <View /> <!-- Item representing search result -->
      <View /> <!-- Item representing search result -->
      <View /> <!-- Item representing search result -->
      <View /> <!-- Item representing search result -->
      <View /> <!-- Item representing search result -->
  </LinearLayout>
</ScrollView>
Run Code Online (Sandbox Code Playgroud)

*)假设从德国应用程序翻译.

Men*_*ene 2

由于 android sdk 中似乎没有标准解决方案,也没有任何公共代码执行此操作,所以我修改了自己的解决方案。这是我的工作解决方案:

我将搜索结果包装在 LinearLayout 中,并使用minimumHeight 来归档所需的行为。这样,当将项目添加到列表中时,我不需要摆弄测量值。

<LinearLayout
  android:id="@+id/scroll_placeholder"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:orientation="vertical"
  >
  <View /> <!-- result -->
  <View /> <!-- result -->
  <View /> <!-- result -->
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

搜索结果是异步检索的,因此我会清除列表并在触发新搜索时启动搜索指示器。此时,我还将最小高度设置为 的可见矩形的大小itemList。请注意,itemList不是 a ScrollView,否则 ScrollView 中会有 ScrollView,这是有问题的。它基本上是一个包含结果的 LinearLayout。

int scrollY = rootScrollView.getScrollY();
if (scrollY > 0) {
    final Rect visibleListViewRect = new Rect();
    placeholder.getGlobalVisibleRect(visibleListViewRect);
    placeholder.setMinimumHeight(visibleListViewRect.height());
} else {
    placeholder.setMinimumHeight(0);
}
Run Code Online (Sandbox Code Playgroud)

这将给出问题的图 3) 中所示的行为。

为了在用户向上滚动后禁用向下滚动(图 4),我添加了一个 ScrollChangedListener:

placeholder.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
    @Override
    public void onScrollChanged() {
        int scrollY = placeholder.getScrollY();
        if (scrollY > 0) {
            final Rect visibleListViewRect = new Rect();
            placeholder.getGlobalVisibleRect(visibleListViewRect);
            placeholder.setMinimumHeight(visibleListViewRect.height());
        } else {
            placeholder.setMinimumHeight(0);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

就是这样。