Search code examples
androidandroid-fragmentsonresumeonpause

Android - Single fragment pause and resume but no destroying


I'm building an application that entirely consists of fragments and a single activity. I have this usecase where every fragment should be initialized once and everytime it is replaced it gets resume/paused. I thought having a single instance of fragment would do the work but its not happening as expected.

I want to know how to achieve this so that only one instance of fragment gets resume/pause everytime.


Solution

  • Use this method to switch Fragments

     void switchFragment(@NonNull Fragment fragment, boolean addToBackStack) {
            final String NAME = fragment.getClass().getName();
            final FragmentManager fm = getSupportFragmentManager();
    
            final boolean fragmentPopped = fm.popBackStackImmediate(NAME, 0);
    
            if (fragmentPopped || fm.findFragmentByTag(NAME) != null) {
                return;
            }
    
            if (addToBackStack) {
                fm.beginTransaction()
                        .replace(mContainerResId, fragment, NAME)
                        .commit();
            } else {
                fm.beginTransaction()
                        .replace(mContainerResId, fragment, NAME)
                        .addToBackStack(NAME)
                        .commit();
            }
        }
    

    And in Fragment class create view like below

    private View rootView;
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
          rootView = inflater.inflate(R.layout.your_layout, container, false);
        }
        return rootView;
    }