简体   繁体   中英

Load Fragments in FragmentpagerAdapter on demand

i had an app with 3 fragments, im using pageadapter so i use an arraylist to load fragment, the problem its, when i add the Arraylist the fragment Load ALL the fragment, after that i load another 2 fragments, in my nexus 4 runs well but some other phones with less HW take a while. in android market seem "load" when you move to page from page, how i can do this? "create" the view only when people change to that page im using the next adapater

public class PagerAdapter extends FragmentPagerAdapter  {

        private final ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
        private final ArrayList<String> titulos = new ArrayList<String>();

        public PagerAdapter(FragmentManager manager) {
            super(manager);
        }


        public void addFragment(Fragment fragment,String title) {
            mFragments.add(fragment);
            titulos.add(title);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

and this is how i load my fragments in FragmentActivity

 mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
        mPagerAdapter.addFragment(new Fragment1(),"Phone");
        mPagerAdapter.addFragment(new Fragment2(),"info");
        mPagerAdapter.addFragment(Fragment3.newInstance() , "none");

From what I understood you have a problem when loading all fragments in phones that do not have much memory. A solution could be switching the FragmentPageAdapter to a FragmentStatePageAdapter . As per Android's FragmentStatePagerAdapter documentation , the StatePageAdapter uses less memory by not keeping the fragments in memory when they are not viewed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM