简体   繁体   中英

Do something on Fragment goes back

I have code that adds a fragment on a click event. This works and the button is removed from display afterwards, but I want the button to appear when the user presses back, and leaves the fragment. Something like onBackStackUsed .

I've tried to find something like it, but i can't find a way to do it. Is it even possible?

final FloatingActionButton floatingActionButton = (FloatingActionButton)findViewById(R.id.live_support);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        getFragmentManager()
            .beginTransaction()
            .replace(R.id.live_support_frame, ChatWindowFragment.newInstance("XXX", "1"), "chat_fragment")
            .addToBackStack("chat_fragment")
            .commit();


        getFragmentManager().addOnBackStackChangedListener(
            new FragmentManager.OnBackStackChangedListener() {
                @Override
                public void onBackStackChanged() {
                    floatingActionButton.setVisibility(View.INVISIBLE);
                }
            }
        );

    }
});

I think what you want is to implement onBackPressed in your activity. Here's a few ways to do it How to implement onBackPressed() in Fragments?

Override onBackPress() method in Activity and manage it like below:

@Override
public void onBackPressed() {
    Fragment myFragment = getSupportFragmentManager().findFragmentByTag("fragment");
    if (myFragment instanceof SearchFragment && myFragment.isVisible()) {
       //do what you want here
    }
}

Happy coding :)

Override onBackPressed inside the activity like this:

@Override
public void onBackPressed() {
    Fragment frag = getSupportFragmentManager().findFragmentByTag("fragment");
    if(frag instanceOf SearchFragment && frag.getTag().equals("chat_fragment")) {
       floatingActionButton.setVisibility(View.INVISIBLE); // or visible
     } else {
        super.onBackPressed();
    }
}
getFragmentManager().addOnBackStackChangedListener(
    new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            int count = getFragmentManager().getBackStackEntryCount();

            if (count == 0) {
                floatingActionButton.show();
            } else {
                floatingActionButton.hide();
            }
        }
    }
);

onBackStachChanged is called both when adding and stack, or removing.
So i'm just checking if there's already one, or not.

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