tags:

views:

149

answers:

2

Hi,

How can I maintain the position of my ListView in my activity when I go to another activity (by launching another intent) and then come back (press the back button)?

Thank you.

+1  A: 
@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);
}
CaseyB
If I use 'getSharedPreferences', does it mean it will persist to the disk? i.e. it will preserve the value after I reboot the phone? What if I don't want that? when I reboot the phone, it will start from 0?
michael
It will persist beyond shutdown. If you do not want that then you can write the value to a member variable and hope that it persists. It should if the app doesn't get garbage collected. You just need to decide which side you'd like to err on.
CaseyB
A: 

You should use onSaveInstanceState to store the scroll position and then use either onCreate or onRestoreInstanceState to restore it.

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

clahey
I tried your way. mListView.getSelectedItemPosition(); return me a -1 and mListView.getScrollY() give me a 0. I am clearly scroll down to my ListView when I do my test. Any idea why it is not working?
michael
What did you do to try my way?
clahey
I did: protected void onSaveInstanceState (Bundle outState) { super.onSaveInstanceState(outState); int scroll = mListView.getScrollY(); System.out.println (" scrollY" + scroll);}
michael
Ah, I have no idea. I haven't used a listView yet. I'm just starting on android.
clahey
Does it work when called from onPause?
clahey
No. It also gives me 0 when I call mListView.getScrollY().
michael
That is the wrong method. You should have been storing myListView.getFirstVisiblePosition() in onPause(), then restoring that position with myListView.setSelection(). Where you store that int is up to you depending on whether you want it to persist after destroy
HXCaine