I am using fragments to design my screen.
When I navigate back to another fragment (from the back stack), the onCreateView(...) method gets called each time even if the fragment has already been created.
How to avoid that the method onCreateView(...) gets called each time and make sure it's called only once (when it's created the first time)?
Asked
Active
Viewed 887 times
1

HiddenDroid
- 1,440
- 4
- 14
- 27
-
Can you include your fragment code in the post. Both, first and second fragments. – UmarZaii Aug 03 '17 at 15:02
1 Answers
3
You can cache your inflated view to the local field if your want. For example:
public class ExampleFragment extends Fragment {
private View fragmentView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
if (fragmentView == null) {
fragmentView = inflater.inflate(R.layout.you_super_view_id, container);
}
return fragmentView;
}
}
But practically, it's ok that pager is reinflating views because it keeps only part of all fragments in memory at the time. So, I think the best idea is to let it work as it should

Anton Potapov
- 1,265
- 8
- 11