有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java避免在片段分页器更改时重新创建相同的视图

当我更改片段页面时,请在InstanceItem中重新创建视图。 我怎样才能避免这种情况

public class ContactPagerAdapter extends PagerAdapter implements IconTabProvider {

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view =null;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.show_content,null);    
        container.addView(view, 0);
        return view;
    }

}

共 (1) 个答案

  1. # 1 楼答案

    改为从^{}扩展:

    FragmentPagerAdapter

    Implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page.

    This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. For larger sets of pages, consider FragmentStatePagerAdapter.

    public static class ContactPagerAdapter extends FragmentPagerAdapter {
        public MyAdapter(FragmentManager fm) {
            super(fm);
        }
    
        @Override
        public int getCount() {
            return NUM_ITEMS;
        }
    
        @Override
        public Fragment getItem(int position) {
           //inflate your fragment here
        }
    }
    

    这将使您的视图保留在内存中,而不是重新创建它们,因此请小心处理的数量