Some confusion on the method instantiateItem(ViewGroup container, int position) of PagerAdapter

Hexor picture Hexor · Jun 6, 2012 · Viewed 11.3k times · Source
public Object instantiateItem(ViewGroup container, int position) {
      ImageView view = new ImageView();
      container.addView(view);
      return view;
}

I read some example code of PagerAdapter, and they all write the addview method. This above is some simple code, And I know 'return view' is used for return the view for display, But what is the container.addView(view) do?

Answer

adamp picture adamp · Jun 6, 2012

Adding the view to the container is actually what makes it appear on-screen. The object returned by instantiateItem is just a key/identifier; it just so happens that using the actual view for this purpose tends to be convenient if you aren't using something like a Fragment to manage the view for the page. (See the source for FragmentPagerAdapter for an example.)

The PagerAdapter method isViewFromObject helps the pager know which view belongs to which key. If you're just returning the view as the key object, you can implement this method trivially as:

public boolean isViewFromObject(View view, Object object) {
    return view == object;
}