避免Fragment在切换时总是重新onCreateView的问题

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">在使用多个Fragment来回切换的时候,总是要重新创建view,结果每次都要重加载数据,无端端让应用变卡,体验很糟糕。</span>

试验了几种方法,目前发现又两个方法不错,可以避免重创建的问题。闲话少叙,正文开始:

Solution One:

原理:缓存已经创建过的view,下次如果发现有,就不再重新创建。注意要判断viewgroup的parent问题。

示例代码:

    private View rootView = null; //缓存fragment的view,避免每次都创建新的

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment, null);
            。。。。。
        }else {
            //缓存的rootView需要判断是否已经在一个ViewGroup中, 如果在,就先移除自己,要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        return rootView;
    

Solution Two:

原理:如果是在ViewPager中使用的Fragment,可以设置ViewPager的OffScreen

示例代码:

mViewPager.setOffscreenPageLimit(3);

官方文档:

Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. Pages beyond this limit will be recreated from the adapter when needed.
This is offered as an optimization. If you know in advance the number of pages you will need to support or have lazy-loading mechanisms in place on your pages, tweaking this setting can have benefits in perceived smoothness of paging animations and interaction. If you have a small number of pages (3-4) that you can keep active all at once, less time will be spent in layout for newly created view subtrees as the user pages back and forth.
You should keep this limit low, especially if your pages have complex layouts. This setting defaults to 1.
大意如下:

这个方法设置了在多个Fragment切换时,当前显示的Fragment左右两边最多保存几个Fragment的页面,默认值是1,也就是说当前页的左右各能保存一个页面。如果切换到了超过保存的页面上去,那么就要根据适配器需要而重新创建所需的Fragment。这个方法的存在意义是为了优化。特别是Fragment数目是已知的情况或者使用懒加载机制的情况。

当然,官方文档已经说明,这个数值最好设置小一点,特别是页面有很复杂的layout。

内存换速度么,呵呵。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章