1

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 this. And here is my code:

public class MainActivity extends FragmentActivity {

    Vector<Fragment> 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<Fragment>();
        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<Fragment> fragments;

        public PagerAdapter(FragmentManager fm, List<Fragment> 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.

BArtWell
  • 4,176
  • 10
  • 63
  • 106
  • 1
    Since ~95% of the sample applications demonstrating `ViewPager` do so by demonstrating using fragment in a `ViewPager`, what *specifically* is confusing you? – CommonsWare Dec 26 '12 at 15:14
  • You should probably rename your class, there is already a PagerAdapter class in Android... – Matthieu Dec 26 '12 at 15:21
  • 1
    And there are a lot of tutorials around on Fragments in ViewPager: http://tamsler.blogspot.com/2011/10/android-viewpager-and-fragments.html, http://thepseudocoder.wordpress.com/2011/10/05/android-page-swiping-using-viewpager/, http://alchemiasoft.wordpress.com/2012/02/15/working-with-fragments-in-a-viewpager/ ... – Matthieu Dec 26 '12 at 15:25
  • @CommonsWare, I confuse with proper managing fragments in memory. Sometimes it detached, MainActivity recreated and I get null from getActivity() method. So, I need make it another way, but I don't know how. – BArtWell Dec 26 '12 at 15:32
  • @Matthieu, Thank's a lot for your links I will look it. – BArtWell Dec 26 '12 at 15:33
  • 1
    @BArtWell Good luck... about your questions with detaching and so on, that's just the way it goes so if you have ASyncTaks or things like that, you'll just have to check if the Fragment is still attached, whether it has a view or things like that, never assume things... – Matthieu Dec 26 '12 at 23:17

1 Answers1

1

Even I had trouble understanding the concept at first and I won't say that I fully understood it. But,

Here's how I am using fragment in my sample application:

Step 1: Creating my Adapter:

public class AllPagesAdapter extends FragmentStatePagerAdapter {



            public AllPagesAdapter(FragmentManager fm) {

                super(fm);

            }

            @Override
            public Fragment getItem(int index) {

        switch (index) {
            case 0:

                return new Fragment1();

            case 1:

                return new Fragment2();
            case 2:

                return new Fragment3();

            case 3:

                return new Fragment4();

            case 4:

                return new Fragment5();


        }
        return null;


    }

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

}

Step 2: In the main activity, I am extending fragment activity and implementing an ActionBar.TabListener. Here's how I am doing it:

public class SomeActivity extends FragmentActivity implements ActionBar.TabListener {

    public ViewPager viewPager;
    private AllPagesAdapter mAdapter;
    private ActionBar actionBar;
    private String [] tabs = {"Fragment1","Fragment2","Fragment3","Fragment4","Fragment5"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Initializing all stuff
        viewPager = (ViewPager)findViewById(R.id.pager);

        actionBar = getActionBar();
        mAdapter = new AllPagesAdapter(getSupportFragmentManager());
        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(true);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);



        //Add the tabs here
        for(String tab_name:tabs){
            actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
        }

        viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){

            @Override
        public void onPageSelected(int position){

                //on Page change, that particular page should be selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
                public void onPageScrolled(int arg0,float arg1,int arg2){

            }
            @Override
        public void onPageScrollStateChanged(int position){

            }

        });
    }



    @Override
    public void onTabSelected(Tab tab, FragmentTransaction fragmentTransaction) {

        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction fragmentTransaction) {



    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction fragmentTransaction) {

        viewPager.setCurrentItem(tab.getPosition());

    }
}

Step 3: I have just one fragment for this example:

Here's the code:

public class Fragment1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        //Can be layout you want it to be.
        View databaseview = inflater.inflate(R.layout.database, container, false);

        return databaseview;

    }

}

Step 4: Last part is the layout: This will be starting point.

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></android.support.v4.view.ViewPager>

Lastly, one important thing is that, number of fragments should be equal to the string array defined in the main activity. If not, the app crashes.

Hope I explained it well..:)

I know this is a very old post but this answer can be used for future viewers.

mike20132013
  • 5,357
  • 3
  • 31
  • 41