0

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

    }
});
Al Lelopath
  • 6,448
  • 13
  • 82
  • 139
Jesper
  • 3,816
  • 2
  • 16
  • 24

4 Answers4

1

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?

Community
  • 1
  • 1
FriendlyMikhail
  • 2,857
  • 23
  • 39
0

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 :)

Anand Savjani
  • 2,484
  • 3
  • 26
  • 39
0

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();
    }
}
Aman Grover
  • 1,621
  • 1
  • 21
  • 41
0
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.

Jesper
  • 3,816
  • 2
  • 16
  • 24