简体   繁体   中英

How to add back pressed button in diffeent fragment?

I using BottomNavigationView with 3 main Fragment, like Fragment [A], [B], [C] . and Fragment [A] is default fragment, if Fragment [B] or [C] press back button must return to Fragment A . In fragment [B] , I add button to get Another fragment just call it Fragment [D] , but if in Fragment D i pressed back button app return into fragment [A] .

So How to return into Fragment [B] when fragment [D] is press back button?

You can work with fragments stack. Implement onBackPressed() in activity.

@Override
public void onBackPressed() {
    //Work with fragments stack...

    int count = getSupportFragmentManager().getBackStackEntryCount();    
    if (count == 0) {
        super.onBackPressed();
    } else {
        getSupportFragmentManager().popBackStack();
    }

}

There is no onBackPressed function from Fragment.
That's why you should define callback interface for backPressed event.

    public interface IFragment {
        boolean onBackPressed();
    }

Then, you should implement your fragment [A], [B], [C], [D].

    @Override
    public boolean onBackPressed() {
        return true;
    }

And you should handle it in your host activity of Fragments.

    @Override
    public void onBackPressed() {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();

        boolean handled = false;
        for(Fragment f : fragments) {
            if(f instanceof IFragment) {
                handled = ((IFragment) f).onBackPressed();
                if(handled) {
                    FragmentManager fm = getSupportFragmentManager();
                    for(String name : fragmentNames) {
                        fm.popBackStack(name, 0);
                    }
                    fm.beginTransaction().commit();
                }
            }
        }

        super.onBackPressed();
    }

I just implemented the code and let you know what you have to know.
Good luck.

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