I have tabView, displaying list in each tab. When I scroll in one tab, switch to another tab and return to previous tab, position is returned to the top instead of displaying pr
Override onSaveInstanceState
to save the position, and set the position back in onRestoreInstanceState
. The Bundle is sort of like a HashMap, (pseudo-code):
In onSaveInstanceState
:
bundle.putInt("MyTabsPosition", getPosition());
Then in onRestoreInstanceState
:
pseudo.setPosition(bundle.getInt("MyTabsPosition"));
To get the current position of your ListView, you can call
int position = mCatchList.getFirstVisiblePosition();
Then once you navigate back to the tab with that ListView, you can call
mCatchList.setSelection(position);
It will depend on how your code is written to tell if the position will need to be added to the savedInstanceState, or however.
In listView.setOnItemClickListener
, use the saveLastPosition
method. And after listview.setAdapter(adapter);
call the getLastPosition
method
public void saveLastPosition(){
int position=listView.getLastVisiblePosition();
SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor=pref.edit();
editor.putInt("lastPosition",position);
editor.apply();
}
public void getLastPosition(){
int position=listView.getLastVisiblePosition();
SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(this);
int lastPosition=pref.getInt("lastPosition",position);
listView.setSelection(lastPosition);
}
Don't call setAdapter() again on the list view. Do something like this.
if(myListView.getAdapter() == null)
myListView.setAdapter(new myAdapter(this, R.layout.row, items));
If you need to update your ListView call notifyDataSetChanged() on the adapter.