Reputation: 3452
I have a ListView in my main page(MainActivity.java) and I want to keep the ListView's position(if it was scrolled up I want to show the exact ListView position) when user comes back to main page.
Since the MainActivity goes to onPause() -> onStop() method when the user clicked a list item, I am saving the state of ListView inside onPause(). For get the return Parcelable value I use a global variable called state.
state = list.onSaveInstanceState(); //line 1
When the user comes back to the MainActivity() it goes through the onStart(), so I get the saved states inside onStart().
if (state != null) {
//set adapter to listview
list.setAdapter(myAdapter);
//Restore previous state
list.onRestoreInstanceState(state);
}
The problem is line 1 doesn't return any state.(It gives a null value). How to fix this?
Thanks.
Upvotes: 0
Views: 7169
Reputation: 78
To get current position of listview you have to implement OnScrollListener and set listener with your listview like,
listView.setOnScrollListener(this);
then, in onScroll method you can do your stuff
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int totalVisibleItem, int totalItemInList) {
// TODO Auto-generated method stub
// here you can save listview's scroll state
// you can see methods parameters
}
and when you get back to your main activity you can use setSelection method of listview like,
listView.setSelection(firstVisibleItem);
i hope this is all you want.
Upvotes: 0
Reputation: 1768
I use this:
Parcelable state = listView.onSaveInstanceState();
before adding the adapter and this:
listView.onRestoreInstanceState(state);
exactly after setting the adapter and I have the result you are looking for. Just try it out
Upvotes: 1