Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

android - How to properly use fragments with ViewPager?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...