2010-04-27 84 views

回答

1
@Override 
protected void onPause() 
{ 
    // Save scroll position 
    SharedPreferences preferences = context.getSharedPreferences("SCROLL", 0); 
    SharedPreferences.Editor editor = preferences.edit(); 
    int scroll = mListView.getScrollY(); 
    editor.put("ScrollValue", scroll); 
    editor.commit(); 
} 

@Override 
protected void onResume() 
{ 
    // Get the scroll position 
    SharedPreferences preferences = context.getSharedPreferences("SCROLL", 0); 
    int scroll = preferences.getInt("ScrollView", 0); 
    mListView.scrollTo(0, scroll); 
} 
+0

如果我使用 'getSharedPreferences',是否意味着它會持續到磁盤?即在我重新啓動手機後它會保留這個值?如果我不想要那個怎麼辦?當我重新啓動手機時,它將從0開始? – michael 2010-04-27 21:38:12

+0

它會持續超出停機。如果你不想這樣做,那麼你可以把值寫入一個成員變量,並希望它保持。它應該如果應用程序沒有收集垃圾。你只需要決定你想犯哪一方。 – CaseyB 2010-04-28 01:09:07

+1

我認爲onPause中的第6行應該讀取editor.putInt(「ScrollValue」,scroll); – Das 2011-09-06 20:48:08

2

您應該使用onSaveInstanceState存儲滾動位置,然後使用onCreateonRestoreInstanceState將其還原。

http://developer.android.com...#onSaveInstanceState ...

+0

我試過你的方式。 mListView.getSelectedItemPosition();返回我一個-1和mListView。getScrollY()給我一個0.當我做我的測試時,我清楚地向下滾動到我的ListView。任何想法,爲什麼它不工作? – michael 2010-04-28 23:26:56

+0

你做了什麼來嘗試我的方式? – clahey 2010-04-29 00:20:44

+0

我做了: 保護無效onSaveInstanceState(Bundle outState){ super.onSaveInstanceState(outState); int scroll = mListView.getScrollY(); System.out.println(「scrollY」+ scroll); } – michael 2010-04-29 00:27:05

27

聲明全局變量:

int index = 0; 
ListView list; 

,並給你ListViewonCreate()參考:

list = (ListView) findViewById(R.id.my_list); 

接下來,在onResume(),加入這一行的結束:

list.setSelectionFromTop(index, 0); 

最後,在,以下行添加到末尾:

index = list.getFirstVisiblePosition(); 
+0

此外,我會將索引保存在sharedPreferences對象中,以便當應用程序超出作用域時,它仍保留索引 – mray190 2015-06-17 13:59:47

+1

@ mray190是保存實例狀態的目的。您可以將此值保存在方向更改的包中,然後在Activity或Fragment級別重新創建視圖時恢復滾動狀態。 – Phil 2015-06-17 14:02:13

2

請注意,使用ListView.getScrollY()無法正常運行的恢復滾動位置。

Android: ListView.getScrollY() - does it work?

它是指整個視圖的滾動量,所以它幾乎總是爲0

它發生在我身上的大部分時間,這個值爲0. ListView.getFirstVisiblePosition()與ListView.setSelection()的工作更可靠。

7

做簡單....

@Override 
protected void onPause() 
{ 
    index = listView.getFirstVisiblePosition(); 
    // store index using shared preferences 
} 

和..

@Override 
public void onResume() { 
super.onResume(); 
// get index from shared preferences 

if(listView != null){ 
    if(listView.getCount() > index) 
     listView.setSelectionFromTop(index, 0); 
    else 
     listView.setSelectionFromTop(0, 0); 
} 
+1

對代碼的解釋可能有所幫助。 – 2012-11-29 09:49:35