Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should getItemPosition consider changes of an item's position?

The documentation for the method getItemPosition in Android's PagerAdapter class states that it is:

Called when the host view is attempting to determine if an item's position has changed.

This method is supposed to be called to indicate whether or not an item's position in the group of items for that adapter has changed.

However, it never states when an overriding method should consider the position to be changed. Does it mean the position is different to the position it was in last time the item getItemPosition was called? Does it mean the item's position is different to last time notifyDataSetChanged was called? Or does it mean that the item's position is different to when the item was added to the viewPager?

like image 248
Macha Avatar asked May 23 '12 21:05

Macha


2 Answers

You can see in ViewPager.java that getItemPosition is called only in dataSetChanged. This means the item's position changed if it's different than the last time dataSetChanged was called.

I would not worry so much about the meaning of "changed"; there are two cases:

  1. The position of the added items never changes, then getItemPosition returns POSITION_UNCHANGED;
  2. The position of the items changes, or items are removed. If the item position did not change, there is no difference if you return POSITION_UNCHANGED or the actual position. So to keep the implementation simple you can return the position (or POSITION_NONE) and forget about POSITION_UNCHANGED..
like image 104
aleb Avatar answered Sep 18 '22 06:09

aleb


By default, the positions of items in a ViewPager are deemed fixed; thats why getItemPosition() by default returns POSITION_UNCHANGED. When you move an item around, ViewPager has to know where to remove an item (the old position of the item) and where to add it. This is what getItemPosition() is used for. It allows you to tell the ViewPager which item to put where, even after your pages have been instantiated.

getItemPosition() is only called when you call notifyDataSetChanged() on your PagerAdapter. By design this means that the "changed" means "changed from when the ViewPager last populated its pages", as notifyDataSetChanged() causes the ViewPager to redraw its children where necessary. In other words: "changed" has either of the meanings you mentioned; whichever one is the most recent to occur.

I think getItemPosition is quite tricky to understand without a sample. See my example of how to use getItemPosition(...) here; I think it'll clarify some things.

like image 20
Reinier Avatar answered Sep 22 '22 06:09

Reinier