Skip to content

Instantly share code, notes, and snippets.

@JesseBuesking
Last active December 18, 2015 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JesseBuesking/5724679 to your computer and use it in GitHub Desktop.
Save JesseBuesking/5724679 to your computer and use it in GitHub Desktop.
Template-ish code for returning a user to the correct position within a ListView in an Android application.
public class ClassWithListView {
/**
* The last index in the list that the user was at.
*/
private int lastIndex = -1;
/**
* Used with lastIndex to match the exact offset.
*/
private int lastIndexOffset = 0;
/**
* Restores the position that the list was at using lastIndex and
* lastIndexOffset.
*
* Remarks:
* Works with dynamic lists as well.
*/
public void restoreListPosition() {
// Use your list's layout here.
final FrameworkListView list = this.getView(R.id.list_layout);
if (null == list) {
return;
}
list.post(new Runnable() {
@Override
public void run() {
int count = list.getAdapter().getCount();
if (count <= ClassWithListView.this.lastIndex) {
list.setSelection(count - 1);
} else {
// Using -1 to show that it's been used. (If you're working
// with a list that dynamically adds items - aka reaching
// the bottom calls for more - we will keep jumping to the
// bottom until the item we were last at is finally
// on-screen. When a user goes further down the list and
// more items are dynamically added, this will be called
// again. If we don't use the -1 logic, it can result
// in the user being jumped back up to the previous index,
// which is mighty annoying).
if (-1 != ClassWithListView.this.lastIndex) {
list.setSelectionFromTop(
ClassWithListView.this.lastIndex,
ClassWithListView.this.lastIndexOffset);
ClassWithListView.this.lastIndex = -1;
}
}
};
});
}
/**
* Keeping track of the last viewed position.
*
* References:
* http://stackoverflow.com/a/8716689/435460
* http://stackoverflow.com/a/3035521/435460
* http://stackoverflow.com/a/5688490/435460
*/
public void saveListPosition() {
final FrameworkListView list = this.getView(R.id.list_layout);
if (null == list) {
return;
}
this.lastIndex = list.getFirstVisiblePosition();
View childToGetOffset = list.getChildAt(0);
this.lastIndexOffset = (null == childToGetOffset)
? 0
: childToGetOffset.getTop();
}
@Override
public void onResume() {
super.onResume();
// This is (most-likely) the point when we want to call to return to
// the correct position. If it doesn't work, then there's likely code
// that's executing after this which updates the list.
this.restoreListPosition();
}
@Override
public void onPause() {
// This is where we save the index position for when we return to the
// list.
this.saveListPosition();
super.onPause();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment