ViewFlipper vs Fragments

dnkoutso picture dnkoutso · Jan 25, 2012 · Viewed 9k times · Source

I have an Activity with a ViewFlipper that flips between a bunch of views (pages) with my data.

I am considering of using the fragments API to switch between my views. What are the benefits of doing so?

Could I see a performance gain by using fragments since the ViewFlipper essentially toggles the visibility flags and fragments actually replace the view hierarchy as you add/remove them?

Can someone give us more insight on this?

Thanks!

Answer

Shawn Lauzon picture Shawn Lauzon · Jan 30, 2012

EDIT: I'm talking about ViewPager here, not ViewFlipper.

The benefit of using a ViewPager is that it's very simple to use. You simply create a FragmentPagerAdapter and fill out a couple simple fields. Below is an example that I wrote to display items that are passed from the parent class.

public static class DashboardPagerAdapter extends FragmentPagerAdapter {

    private static final int NUM_ITEMS_PER_SCREEN = 12;

    private List<View> mAllItems;
    private int mNumScreens;

    public DashboardPagerAdapter(FragmentManager fm, List<View> allItems) {
        super(fm);
        mAllItems = allItems;
        mNumScreens = (int) Math.ceil(mAllItems.size()
                / (float) NUM_ITEMS_PER_SCREEN);
        Log.d(TAG, "num screens: " + mNumScreens);
    }

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

    @Override
    public Fragment getItem(int position) {
        DashboardScreenFragment screen = DashboardScreenFragment
                .newInstance();

        for (int i = position * NUM_ITEMS_PER_SCREEN; i < (position + 1)
                * NUM_ITEMS_PER_SCREEN; i++) {
            if (i >= mAllItems.size()) {
                break;
            }
            screen.addChild(mAllItems.get(i));
        }
        return screen;
    }
}

And setting it up is super simple:

    final DashboardPagerAdapter adapter = new DashboardPagerAdapter(
            getFragmentManager(), mAllButtons);

Contrary to what @sebap123 said, you can use Fragments with Android v4 and above with the Support Library; see http://developer.android.com/sdk/compatibility-library.html for details, but it really just involves putting the jar file in your /libs directory.

BTW, note that with ViewPager, each "page" is itself a Fragment.

As for whether there is a performance improvement, that depends on what you're comparing it to. I highly recommend trying out ViewPager and only after worrying about performance problems. As Donald Knuth said, "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."

In any case, if you have a large number of pages, see http://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter.html for a more appropriate adapter.