Android – How to show the last item in the List View when scrolled to get new items dynamically

androidandroid-listview

I have a list view in my app which shows 10 items initially, and when i scroll to the bottom, it dynamically adds 10 items every time. My problem is when i scroll to the bottom, the display goes to the 1st item in the list(not the newly added 10 items), so i need to scroll all the way down.

I used

ListView.setSelection(totalItemCount - 9);

to display the 1st item of the newly added 10 items. But here what happens is the display goes to the 1st item of the listview actually, but again it automatically scrolls to the 1st item of the newly added 10 items. so, the ux will be bad here….i want it to change so that it whould not go to the top of the listview. hope i explained it clearly, please help, thankyou

Best Answer

When you scroll down and start getting new data you should store your Last Visible Position in some variables using this method :

int firstVisiblePosition = listView.getFirstVisiblePosition();

Edit Try this :

View view = listView.getChildAt(0);
int distFromTop = (view == null) ? 0 : view.getTop();

Then after you completed loading data you should set this position using :

listView.setSelectionFromTop(firstVisiblePosition, distFromTop);
Related Topic