简体   繁体   中英

Switching fragments: should I add some action?

I have two fragments FirstFragment() and SecondFragment() and a frame R.id.frame . In my code, I need to switch often between FirstFragment() and SecondFragment() inside the frame R.id.frame . To do that, I use the following code.

getSupportFragmentManager().beginTransaction()
    .replace(R.id.frame, new SecondFragment()).addToBackStack(null).commit();

According to the best practices, is this code enough? Or should I add some other action? For example, destroy the old fragment , delete it or what.

replace() = remove(FirstFragment) + add(SecondFragment)

As soon as first fragment is removed, it will be eligible for garbage collection. No extra actions required from developer.

You should be using show and hide after adding your fragments. This will not re-create your fragments everytime you switch between fragments.

private void addFragment(Fragment fragment, Class<? extends Fragment> tag) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.content, fragment, tag.getSimpleName()).addToBackStack(tag.getName()
        ).commit();
    }
private void showFragment(Fragment fragment) {
        if (fragment == null) {
            return;
        }
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.show(fragment).commit();
    }

private void hideFragment(Fragment fragment) {
        if (fragment == null) {
            return;
        }
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();
        transaction.hide(fragment).commit();
    }

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