13
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?

Amt87
  • 5,493
  • 4
  • 32
  • 52
Hexor
  • 525
  • 1
  • 8
  • 22

2 Answers2

21

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;
}
adamp
  • 28,862
  • 9
  • 81
  • 69
1

As per comments include in Source Code of PageAdapter

public abstract Object instantiateItem(View container, int position);    

Create the page for the given position. The adapter is responsible for adding the view to the container given here, although it only must ensure this is done by the time it returns from

Container The containing View in which the page will be shown.

Position The page position to be instantiated.

Returns an Object representing the new page.This does not need to be a View, but can be some other container of the page.

Vipul
  • 27,808
  • 7
  • 60
  • 75