ViewFlipper vs Fragments

孤街醉人 提交于 2019-11-30 13:33:09

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!