How to avoid recreating view on onCreate on Android?

前端 未结 11 1764
执笔经年
执笔经年 2021-01-17 22:18

I have a FragmentActivity that shows a contacts list.

Here is my onCreate method:

@Override
protected void onCreate(Bundle          


        
11条回答
  •  梦毁少年i
    2021-01-17 23:03

    I have faced similar issue once. I am not sure how legitimate this is but the code I have used is below and it fixed a lot:

    private static ViewGroup view1;
    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            mCurrentActivity = getActivity();
            if (view1 == null) {
                settleFragment(inflater);
            } else {
                if (view1.getParent() != null && view1.getParent() instanceof ViewGroup) {
                    ((ViewGroup) view1.getParent()).removeView(view1);
                }
            }
            return view1;
        }
    

    You can adapte settleFragment(inflater); method with yours. The magic is about static variable named view1. Once the fragment is initialised it is filled up with the data. The other instances of Fragments will simply rip apart view1 from its ex-parent and will paste it on themself.

    It is pretty fast with respect to file storage cache since the object is kept in ram. If OS garbage collects the object, static variable will be null again and while recreating the view no duplicates will occur.

提交回复
热议问题