Deprecated PagerAdapter.instantiateItem() method

Juan Andrés Diana picture Juan Andrés Diana · Dec 12, 2013 · Viewed 8.3k times · Source

I'm curious as to why instantiateItem was deprecated in favor of it's newer version. The change is that it now receives ViewGroup in stead of a more general View.

Deprecated method

public Object instantiateItem (View container, int position)

New method

public Object instantiateItem (ViewGroup container, int position)

Note: This change also happened to destroyItem, startUpdate, finishUpdate & setPrimaryItem.

Answer

Scott W picture Scott W · Dec 12, 2013

My guess is that it was done because those methods are always called with a ViewGroup rather than the more general View. As such, providing the parameter as a ViewGroup is a convenience, allowing developers to avoid always checking and casting the input. So instead of seeing this code over and over:

ViewGroup parent;
if (container instanceof ViewGroup) {
    parent = (ViewGroup) container;
}
else {
    throw new IllegalArgumentException("container must be a ViewGroup");
}

The implementer can simply use container directly.

And, in fact, you can see that this is exactly the reason in the commit message from Adam Powell:

Bug 5327146 - ViewPager API tweaks and docs

PagerAdapter previously took View instances as parameters to several of its methods leading to lots of casting to ViewGroup in adapter implementations.

Change these to take ViewGroups. Default implementation calls through to deprecated stubs with the existing signatures, allowing current adapters to keep working unmodified.