0

While adding user interface to a fragment it is shown to inflate the view each an every call to onCreateView:

public static class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}

reference: http://developer.android.com/guide/components/fragments.html#UI

What if I cache the view inflated and return it on next calls such as:

public static class ExampleFragment extends Fragment {
    private View mView = null;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(mView == null){
            mView = inflater.inflate(R.layout.example_fragment, container, false);
        }else{
            //detach mView from previous parent if exist
            ...
        }
        return mView;
    }
}
guness
  • 6,336
  • 7
  • 59
  • 88
  • 1
    you do not need such things, android handles that itself, more specifically why would you do that ? – TootsieRockNRoll Oct 13 '14 at 08:37
  • @ElJazouli I am using 'getFragmentManager().beginTransaction().replace()' and ExampleFragment#onCreateView is called every time I replace a fragment, even if I used it before. Am I doing something wrong? – guness Oct 13 '14 at 08:45
  • 1
    no because replace replaces your fragment with another one, and when you press BACK it i recreated, you might want to use .add() instead of .replace(), it will remain in memory, but you'll want to be more careful with that – TootsieRockNRoll Oct 13 '14 at 08:53

1 Answers1

5

Fragment manager already handles such optimizations for you.

onCreateView() is only called when the fragment view needs to be created. When it's already created in a usable state, onCreateView() won't be called.

laalto
  • 150,114
  • 66
  • 286
  • 303
  • I am using 'getFragmentManager().beginTransaction().replace()' and ExampleFragment#onCreateView is called every time I replace a fragment, even if I used it before. Am I doing something wrong? – guness Oct 13 '14 at 08:45
  • Replacing a fragment removes the old fragment and destroys its view and creates a view for the new fragment. That's how it works. – laalto Oct 13 '14 at 08:49