How to avoid the layout inflation each time a fragment transaction is committed?

932 Views Asked by At

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)?

1

There are 1 best solutions below

0
On

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