2012-03-21 65 views

回答

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(); 
     } 
     ...................... 
     ......................      
} 

就是這樣!我希望這對一個人有幫助。 :)

+0

不要你需要有setRetainInstance(真),以便能夠保持整數那裏的片段? – 2013-01-29 10:33:29

+0

但我onPause和onResume語句沒有工作 – Vikky 2013-06-27 09:55:08

+0

爲什麼你捕捉'Throwable'? – 2014-04-11 03:01:16

0

嘗試

listView.getFirstVisiblePosition() 
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 
     ); 
    } 
} 
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(); 
    }       
} 
相關問題