ViewFlipper vs Fragments

前端 未结 1 1750
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-02 09:33

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 view

相关标签:
1条回答
  • 2021-01-02 09:49

    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.

    0 讨论(0)
提交回复
热议问题