片段内的ListView无法保存滚动位置

时间:2012-03-21 11:19:18

标签: android

ListView位于ListView内时,如何保存ListFragment的滚动位置?

4 个答案:

答案 0 :(得分:19)

最后我解决了这个问题,所以我决定为其他人发布解决方案:

在我的ListFragment子类中,我声明了两个int变量来保存滚动位置

public static class MyListFragment extends ListFragment {

        ......................
            ......................
        private int index = -1;
        private int top = 0;
            ......................

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

@Override
public void onResume() {
      super.onResume();
      ......................
      ......................
      setListAdapter(mAdapter);
      if(index!=-1){
         this.getListView().setSelectionFromTop(index, top);
      }
      ......................
      ......................

}

@Override
public void onPause() {
      super.onPause();
      try{
         index = this.getListView().getFirstVisiblePosition();
         View v = this.getListView().getChildAt(0);
         top = (v == null) ? 0 : v.getTop();
      }
      catch(Throwable t){
         t.printStackTrace();
      }
      ......................
      ......................                    
}

就是这样!我希望这对一些人有所帮助。 :)

答案 1 :(得分:2)

我认为您的解决方案适用于触摸模式,但对我来说还不够。我需要将选择器放在相同的选定项目上,而不是第一个可见的项目:

@Override
public void onStop() {
    super.onStop();
    ListView listView = this.getListView();
    lastPosition = listView.getSelectedItemPosition();
    int lastPositionInGroup = lastPosition - listView.getFirstVisiblePosition();
    lastTop = listView.getChildAt( lastPositionInGroup ).getTop();
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    /* cursor adapter stuff here */

    if (lastPosition != AdapterView.INVALID_POSITION) {
        listView.setSelectionFromTop(
                lastPosition,
                lastTop != AdapterView.INVALID_POSITION ? lastTop : 0
        );
    }
}

答案 2 :(得分:0)

尝试

listView.getFirstVisiblePosition()

答案 3 :(得分:0)

    @Override
public void onResume() 
{
      super.onResume();
      if(CommonVariables.firstsel==6)
      {
          swipelistview.setAdapter(adapter_ct);
          swipelistview.setSelection(CommonVariables.index);
      }
 }

@Override
public void onPause()
{
    super.onPause();          
    try
    {
        CommonVariables.firstsel=6;
        CommonVariables.index = Fragmentct.swipelistview.getFirstVisiblePosition()+1;       
        Toast.makeText(getActivity(),"onPause"+CommonVariables.index,1500).show();
    } 
    catch(Throwable t){
        t.printStackTrace();
     }                        
 }