Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android PagerAdapter not calling instantiateItem

I'm trying to implement ViewPager with PagerAdapter in my app. I'm mainly working off this example.

My PagerAdapter is called DataPagerAdapter and uses the following constructor and instantiateItem, where I inflate a view from data_list_view.xml:

public class DataPagerAdapter extends PagerAdapter
    implements TitleProvider {
    private LayoutInflater mInflater;
    
    private static String[] titles = new String[]
    {
        "Page 1",
        "Page 2",
        "Page 3"
    };
    private final Context context;
 
    public DataPagerAdapter( Context context )
    {
        this.context = context;
    }
 
    @Override
    public String getTitle( int position )
    {
        return titles[ position ];
    }
 
    @Override
    public int getCount()
    {
        return titles.length;
    }
 
    @Override
    public Object instantiateItem( View pager, int position )
    {
        ListView v = (ListView) mInflater.inflate(R.layout.data_list_view, null);
        ((ViewPager)pager).addView( v, 0 );
        return v;
    }
 
    @Override
    public void destroyItem( View pager, int position, Object view )
    {
        ((ViewPager)pager).removeView( (ListView)view );
    }
 
    @Override
    public boolean isViewFromObject( View view, Object object )
    {
        return view.equals( object );
    }
 
    @Override
    public void finishUpdate( View view ) {}
 
    @Override
    public void restoreState( Parcelable p, ClassLoader c ) {}
 
    @Override
    public Parcelable saveState() {
        return null;
    }
 
    @Override
    public void startUpdate( View view ) {}
}

And in my activity I get my adapter:

DataPagerAdapter adapter = new DataPagerAdapter( this );

And then later I want to refer to my dataListView in code:

dataListView = (ListView) findViewById(R.id.listViewData);

Problem is, the dataListView is returned as null by the findViewById call since the instantiateItem is never processed.

When is instantiateItem called and is this done automatically (as the example seems to suggest) or do I have to force it somehow?

like image 840
mraviator Avatar asked May 04 '12 20:05

mraviator


2 Answers

Note, that your adapter uses deprecated methods:

public Object instantiateItem(View container, int position)
public void destroyItem(View container, int position, Object object)

The API says to use these instead:

public Object instantiateItem(ViewGroup container, int position)
public void destroyItem(ViewGroup container, int position, Object object)
like image 52
Vit Khudenko Avatar answered Oct 20 '22 04:10

Vit Khudenko


In my case the problem was I set ViewPager visibility to GONE by mistake and it was not getting called . Just make viewPager visibility to visible in layout.

like image 39
Manohar Avatar answered Oct 20 '22 03:10

Manohar