1

I've been experimenting with ViewPager in Android and noticed that PagerAdapter does not instantiate the "page" views until after onCreate() has finished in my main Activity. This seems to make it impossible to hook up any listeners to any layout widgets or callbacks from the main Activity. Is there a method that gets called after onCreate() that I can hook into in order to access the instantiated views from PagerAdapter? OnPostResume() and OnPostCreate() do not seem to get called.

main activity

public class mainApp extends Activity
{
    protected void onCreate (Bundle savedInstanceState)
    {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.main);

        mAdapter = new MyPagerAdapter ();
        mPager = (ViewPager) findViewById (R.id.myfivepanelpager);
        mPager.setAdapter (mAdapter);
        mPager.setCurrentItem (1);

        /* here, I would like to be able to inflate the views 
         * instantiated in mAdapter, however they have not been 
         * instantiated yet even though setCurrentItem() has been called */
    }

    ...
}

PagerAdapter

public class MyPagerAdapter extends PagerAdapter
{
    private String TAG = "** MyPagerAdapter **";
    View vscreen1;
    View vscreen2;

    @Override
    public int getCount ()
    {
        return 2;
    }


    @Override
    public int getItemPosition (Object object)
    {
       return super.getItemPosition (object);
    }


    public Object instantiateItem (View collection, int position)
    {
        LayoutInflater inflater = (LayoutInflater) collection.getContext ().getSystemService (Context.LAYOUT_INFLATER_SERVICE);
        int resId = 0;

        switch (position)
        {
            case 0:
                  resId = R.layout.screen1;
                        Log.d (TAG, "screen1");
                  // tie in button callbacks here for screen1
            break;

            case 1:
                        resId = R.layout.screen2;                               
                        Log.d (TAG, "screen2");
                  // tie in button callbacks here for screen2
            break;
        }

        View view = inflater.inflate (resId, null);
        ((ViewPager) collection).addView (view, 0);


        return view;
    }

   ...

}   
wufoo
  • 13,571
  • 12
  • 53
  • 78
  • 3
    Off the cuff, you should be configuring your widgets when you create them, in `instantiateItem()`. Personally, I use fragments as my `ViewPager` pages, and the fragments are then responsible for widget configuration. – CommonsWare Jun 20 '12 at 17:13
  • Hmm.. I've been seeing a lot of example code with Fragments so guess I'll give that a shot. Thanks. – wufoo Jun 20 '12 at 17:26

0 Answers0