从onCreate访问ViewPager视图?

时间:2012-06-20 17:11:32

标签: android android-viewpager

我一直在尝试使用Android中的ViewPager,并注意到PagerAdapter在 onCreate()之后在我的主Activity中完成后才会实例化“页面”视图。这似乎使得无法将任何侦听器连接到主Activity的任何布局小部件或回调。是否有一个方法可以在onCreate()之后调用,我可以挂钩以便从PagerAdapter访问实例化的视图? OnPostResume()和OnPostCreate()执行而不是似乎被调用。

主要活动

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;
    }

   ...

}   

0 个答案:

没有答案