简体   繁体   中英

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.

Use this method to switch Fragment s

 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM