【问题标题】:Save ListView Scroll Position in the Same Activity将 ListView 滚动位置保存在同一个 Activity 中
【发布时间】:2015-05-06 09:21:30
【问题描述】:

我有一个很长的ListView 带有编辑文本,用户可以在片段中滚动。当用户停止滚动并返回到同一片段中的列表时,我希望列表滚动到与它相同的点以前是。 如果 ListView 有 20 行,并且用户在第 5 行输入了值,向下滚动并返回后,光标应该位于第 5 行。

我正在使用来自ListFragmentListView,并且我有一个自定义adapter,它扩展了填充L​​istView 的ArrayAdapter。我不能使用 onSaveInstanceState 和 onActivityCreated,因为我没有离开 Fragment。

如何存储ListView 当前位置以供以后使用?

【问题讨论】:

标签: android android-listview


【解决方案1】:

当您触发操作时,您现在可以通过以下方式为用户获取列表视图中的第一个可见项目位置:

int position = listview.getFirstVisiblePosition();

如果您想稍后再次设置滚动位置,请使用以下命令:

listview.smoothScrollToPosition(position);

你可以使用SharedPReferences来存储这个位置,以防你想长时间存储它(不止一个会话)。

注意:如果您的列表是通用的并且以后可能会更短以避免indexOutOfBound 崩溃,请注意您存储的位置。

有关如何使用SharedPreferences 的更多信息,请访问link

【讨论】:

    【解决方案2】:

    我知道的最佳解决方案

    // 将 ListView 状态(= 包括滚动位置)保存为 Parceble

    Parcelable state = listView.onSaveInstanceState();
    

    // 恢复之前的状态(包括选中项索引和滚动位置)

    listView.onRestoreInstanceState(state);
    

    即使将适配器设置为-也可以恢复上次保存的位置

    // Save the ListView state (= includes scroll position) as a Parceble
    Parcelable state = listView.onSaveInstanceState();
    
    // e.g. set new items
    listView.setAdapter(adapter);
    
    // Restore previous state (including selected item index and scroll position)
    listView.onRestoreInstanceState(state);
    

    您也可以参考here了解更多详情。

    【讨论】:

    • 嗨,在 onCreate() 或 onResume() 中使用此代码的位置
    【解决方案3】:

    在 ListFragment 片段中声明两个 int 变量来保持滚动位置:

    public static class MyListFragment extends ListFragment {
    
            private int listIndex = -1;
            private int listTop = 0;
    

    然后重写onPause()和onResume()来保存和恢复ListView的滚动位置如下:

    @Override
    public void onResume() {
          super.onResume();
    
       //after setting adapter and your arbitrary codes
          if(listIndex!=-1){
             this.getListView().setSelectionFromTop(index, top);
          }
    
    }
    
    @Override
    public void onPause() {
          super.onPause();
          try {
            listIndex = getListView().getFirstVisiblePosition();
            View v = getListView().getChildAt(0);
            listTop = (v != null) ? v.getTop() : 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
    
    }
    

    希望减轻痛苦! :脸红:

    【讨论】:

      猜你喜欢
      • 2012-06-26
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多