开发者

Getting the position of a non-visible ListItem

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() and getChildAt(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 of getChildCount() 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 when index >= getChildCount().开发者_Python百科

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 ListAdapter using int getCount() and Object getItem(int position) until you find the object with your desired ID, then use the current position as argument to ListView.smoothScrollToPosition(int position).

Not very efficient but should have the desired effect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜