Search code examples
androidandroid-fragmentsinterfacecallbackonbackpressed

How to have an Activity notify a Fragment that the back button has been pressed


I have been researching this for a few days and have yet to find a working solution. There is lots of information available but because of my inexperience with Android I can't get any of the suggestions to work.

I have an Activity with a stack of 3 Fragments on top of it all of which are presented using FragmentManager Transactions and added to the backstack. While the third Fragment is active, I need to intercept the onBackPressed() method and perform some extra stuff before the Fragment is destroyed.

I have tried using Callbacks and Interfaces to capture onBackPressed() at the Activity and send it to the 3rd Fragment with no luck.

What is the proper way to have a Fragment deep in the stack watch for the Activity's onBackPressed() method.

Let me know if this is not clear.

Thanks for the help.


Solution

  • This is the post that answered my question. For a Android newbie, this told me where everything needed to go.

    https://stackoverflow.com/a/30865486/2640458

    The Fragment that needed to see the onBackPress() method from it's activity:

    public class RatingFragment extends Fragment implements ContentActivity.OnBackPressedListener  {
    
    @Override
    public void doBack() {
        getFragmentManager().popBackStack();
    }
    

    The very important subscription to the listener in the above Fragment:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_rating, container, false);
    
        ((ContentActivity)getActivity()).setOnBackPressedListener(this);
    }
    

    The Activity that needs to send the onBackPress() method to the above Fragment:

    public class ContentActivity extends Activity {
    
    protected OnBackPressedListener onBackPressedListener;
    
    public interface OnBackPressedListener {
        void doBack();
    }
    
    public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
        this.onBackPressedListener = onBackPressedListener;
    }
    
    @Override
    public void onBackPressed() {
        if (onBackPressedListener != null)
            onBackPressedListener.doBack();
        else
            super.onBackPressed();
    }
    
    @Override
    protected void onDestroy() {
        onBackPressedListener = null;
        super.onDestroy();
    }
    }