The case:
I have a ListView with a variable amount of ListItems (e.g. 20). At first items 0-6 are visible. The user now scrolls down the list and clicks item nr. 15. A new activity starts, and at some point the user hits the back button. Now item nr. 15 might be at the same position, have had its position changed or have been deleted (Handling the deleted situation is not the problem). The other two situations will have equal behaviour, apart from how the list is re-populated (which is not the problem either).
What I would like to do:
Upon returning to the ListView from item nr. 15, I have saved an ID for the item (using setResult and onActivityResult) and the ListView is re-populated with items. (The item in question, here nr. 15, will always be in the list after re-population)
I then want to scroll the list down to the position of item nr. 15, making item nr. 15 the first visible item in the ListView.
The problem:
- Using the methods
getChildCount()andgetChildAt(index)does not
solve my problem, as the desired item might be out of view (not shown
in the list, but in the datacore of the listadapter). - Using the method
getCount()instead ofgetChildCount()gives me the right number of items in the list – but as soon as I run through the items in a for-loop I run into a NullPointerException whenindex >= getChildCount().
My question:
- How can I run through all items (visible in list or not) and when I find the item that meets my requirements, scroll the listview making that item the first visible item?
You could iterate over your
ListAdapterusingint getCount()andObject getItem(int position)until you find the object with your desired ID, then use the current position as argument toListView.smoothScrollToPosition(int position).Not very efficient but should have the desired effect.