Fragment - should I reuse view in onCreateView and how should I do that?

前端 未结 3 1182
生来不讨喜
生来不讨喜 2021-02-04 09:31

Actually, I always reused my view in my fragments like the following:

private View mView = null;

@Override
public View onCreateView(LayoutInflater inflater, Vie         


        
3条回答
  •  忘了有多久
    2021-02-04 09:59

    I know it's a old question. But after working with fragments for months, I found one thing need to mention when using cache this way is that: if your current cached layout still has another fragment tag, this cache strategy will lead to the embed fragment loss some life-cycle callback. I'll talk it in detail:

    1.The current fragment onCreateView was called first time. By caching like above, we will inflate the target layout(this layout including a fragment tag). 2.By inflater.inflate this will make the embed fragment added to the layout correctly, the onCreateView will be called. 3.When current fragment needs to be destroy, the embed fragment onDestroyView will be called correctly.

    4.When current fragment onCreateView called again, we return a cached view, without calling inflater.inflate. You will find the embed fragment onCreateView and onDestroyView or other life-cycle methods won't be called.

    That's all what I want to mention.

提交回复
热议问题