How to properly use fragments with ViewPager?

admin

Administrator
Staff member
I know many applications using fragments in ViewPager. I need it in my application too. I have no found any guide how I can to do it exclude <a href="http://thepseudocoder.wordpress.com/2011/10/05/android-page-swiping-using-viewpager/" rel="nofollow">this</a>. And here is my code:

Code:
public class MainActivity extends FragmentActivity {

    Vector&lt;Fragment&gt; fragments;
    ViewPager viewPager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        viewPager = (ViewPager) findViewById(R.id.pager);

        fragments = new Vector&lt;Fragment&gt;();
        fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
        fragments.add(Fragment.instantiate(this, Fragment2.class.getName()));

        viewPager.setOffscreenPageLimit(fragments.size());
        PagerAdapter pagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);

        viewPager.setAdapter(pagerAdapter);

        viewPager.setCurrentItem(0);
    }

    class PagerAdapter extends FragmentPagerAdapter {

        private List&lt;Fragment&gt; fragments;

        public PagerAdapter(FragmentManager fm, List&lt;Fragment&gt; fragments) {
            super(fm);
            this.fragments = fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return this.fragments.get(position);
        }

        @Override
        public int getCount() {
            return this.fragments.size();
        }

    }

}

But this code doesn't working well. Sometimes I get error in my Fragment1 about getActivity() return null. I read many posts from this site and other about this error and now I know that is bad way - use Vector for storing fragments. But I still don't know, how to do ViewPager with fragments properly. Please, help.