Skip to content

Instantly share code, notes, and snippets.

@lalongooo
Created May 28, 2015 06:49
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 lalongooo/95fbda3ebeaeff865438 to your computer and use it in GitHub Desktop.
Save lalongooo/95fbda3ebeaeff865438 to your computer and use it in GitHub Desktop.
Add new items to top of an android ListView
//Method onRefresh() from SwipeRefreshLayout.OnRefreshListener
@Override
public void onRefresh() {
// I'm using Retrofit, so this is the way I get new data from the server
new RestAdapter().get().getItems(new Callback<List<Foo>>() {
@Override
public void success(List<Foo> foos, Response response) {
// IMPORTANT: This is important to add new items at the top of the listview
adapter.addMoreItems(0, foos);
int index = listView.getFirstVisiblePosition() + foos.size();
int top = (listView.getChildAt(0) == null) ? 0 : listView.getChildAt(0).getTop();
adapter.notifyDataSetChanged();
listView.setSelectionFromTop(index, top);
swipeRefreshLayout.setRefreshing(false);
}
@Override
public void failure(RetrofitError error) { }
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment