Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 809
Hexor Avatar asked Jun 06 '12 04:06

Hexor


2 Answers

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;
}
like image 91
adamp Avatar answered Oct 01 '22 04:10

adamp


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.

like image 42
Vipul Avatar answered Oct 01 '22 03:10

Vipul