避免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。

內存換速度麼,呵呵。

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