如何保存ListView的滚动位置

6

当我在ListView中选择一个项目并希望返回到相同的ListView时,如何保存ListView的滚动位置。

假设我们有两个片段 - ListFragment和SomeOtherFragment。我们用SomeOtherFragment替换ListFragment。

    FragmentManager manager = getFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();

    transaction.replace(R.id.content_frame, fragment);
    transaction.addToBackStack(null);
    transaction.commit();
2个回答

2
当你点击ListFragment的行时,在SharedPreference中保存位置。
<shared_pref_object>.putInt("scroll_position",position);

当你从OtherFragment返回到ListFragment时,请使用此方法。

<editor_obj>.getInt("scroll_position",0);

将此设置为滚动位置:

listview.setSelection(<editor_obj>.getInt("scroll_position",0));

0
我真的很想知道为什么对于这个常见的问题,没有一个好的和优化的解决方案。就我所看到的,每个人都用自己的方式解决了它。但是在尝试了所有方法之后,我想呈现我的方法:
在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();
    }

}

希望能减轻痛苦!:blush:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接