android. How to conserve memory with custom ArrayAdapters and ViewPagers

帅比萌擦擦* 提交于 2019-12-07 15:20:26

If you are really sure that having lots of static fragments in memory consumes a huge amount of memory, maybe you could try something like this:

Instead of using:

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position);
    }

You could actually declare a Map of fragment. The main goal is to re-use previously created fragments, than keep declaring new instance. Firstly, declare this code on fragment's activity (NOT in SectionsPagerAdapter):

private Map<Integer, PlaceholderFragment> mPlaceHolderFragmentArray = new LinkedHashMap<Integer, PlaceholderFragment>(); 

Then replace getItem(int position) method in SectionsPagerAdapter with this:

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        PlaceholderFragment fragment = mPlaceHolderFragmentArray.get(position);
        if(fragment == null){
            fragment = PlaceholderFragment.newInstance(position);
            mPlaceHolderFragmentArray.put(position, fragment);
        }
        return fragment;
    }

I don't know if there are any better way, but I'm currently using this on my codes.

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