0

So in my fragment I have a toolbar back button but I also have the phone's back button. When I tap on the toolbar one I need to just call the activity's onBackPressed and when I tap on phone's back button some specific functionality needs to happen. How do I override onBackPressed() method in the activity to handle both cases and use it in fragment as well?

alexC
  • 133
  • 1
  • 12
  • 1
    You can achieve this by checking for the system hardware back button like described here: https://stackoverflow.com/questions/8094715/how-to-catch-event-with-hardware-back-button-on-android – Mark P. Dec 10 '19 at 15:47
  • Does this answer your question? [How to implement onBackPressed() in Fragments?](https://stackoverflow.com/questions/5448653/how-to-implement-onbackpressed-in-fragments) – Quinn Dec 10 '19 at 16:07

1 Answers1

0

Do you have a way to track the fragments? Assuming you have the fragment tag set while loading it.

        int _contentContainerId;
        String sFragmentTag

        // Get the fragment manager
        FragmentManager fm = getSupportFragmentManager();

        // Change the container based on the parameters
        _contentContainerId = (nViewId == 0) ? R.id.container_application : nViewId;

        // Check if a fragment already exists. 
        Fragment currentFragment = fm.findFragmentById(_contentContainerId);

        // if it does not exist, then add the fragment, else replace it
        if (currentFragment == null) {
            fragTrans.add(_contentContainerId, fragmentObject, sFragmentTag);
        } else {
            fragTrans.replace(_contentContainerId, fragmentObject, sFragmentTag);
        }

In your Activity which is the container for the fragments

@Override
public void onBackPressed() {
    String currentFrag = getCurrentFragment(this, Constants.FRAG_CONTAINER_ID);

    if (currentFrag.equalsIgnoreCase()) {
        //your backpress logic for the fragment
    } else if (...) {

    } else {
        //normal backpress
        super.onBackPressed();
    }
}
}

public String getCurrentFragment(Context ctx, int containerId) {
    Fragment currentFrag;
    currentFrag = ((FragmentActivity) ctx).getSupportFragmentManager().findFragmentById(containerId);
    if (currentFrag != null) {
        String currentFragTag = currentFrag.getTag();
        if (StringUtils.isNotBlank(currentFragTag))
            return currentFragTag;
        else
            return "";
    } else {
        return "";
    }
}
usr30911
  • 2,731
  • 7
  • 26
  • 56