How To Maintain The Position Of Listview
Possible Duplicate: Maintain/Save/Restore scroll position when returning to a ListView How can I maintain the position of my ListView in my activity when I go to another activit
Solution 1:
Declare global variables:
intindex = 0;
ListView list;
and make a reference to your ListView
in onCreate()
:
list = (ListView) findViewById(R.id.my_list);
Next, in onResume()
, add this line at the end:
list.setSelectionFromTop(index, 0);
Lastly, in onPause
, add the following line to the end:
index = list.getFirstVisiblePosition();
Solution 2:
Do simple....
@OverrideprotectedvoidonPause()
{
index = listView.getFirstVisiblePosition();
// store index using shared preferences
}
and..
@Override
public void onResume() {
super.onResume();
// get index from shared preferencesif(listView != null){
if(listView.getCount() > index)
listView.setSelectionFromTop(index, 0);
else
listView.setSelectionFromTop(0, 0);
}
Solution 3:
You should use onSaveInstanceState
to store the scroll position and then use either onCreate
or onRestoreInstanceState
to restore it.
Solution 4:
Please note that using ListView.getScrollY() DOES NOT WORK WELL for restoring the scroll position.
See Android: ListView.getScrollY() - does it work?
It is referring to the scroll amount of the entire view, so it will almost always be 0.
It happened to me too most of the time that this value was 0. ListView.getFirstVisiblePosition() with ListView.setSelection() works more reliably.
Solution 5:
@OverrideprotectedvoidonPause()
{
// Save scroll positionSharedPreferencespreferences= context.getSharedPreferences("SCROLL", 0);
SharedPreferences.Editoreditor= preferences.edit();
intscroll= mListView.getScrollY();
editor.put("ScrollValue", scroll);
editor.commit();
}
@OverrideprotectedvoidonResume()
{
// Get the scroll positionSharedPreferencespreferences= context.getSharedPreferences("SCROLL", 0);
intscroll= preferences.getInt("ScrollView", 0);
mListView.scrollTo(0, scroll);
}
Post a Comment for "How To Maintain The Position Of Listview"