How to implement onBackPressed() in Fragments? How to implement onBackPressed() in Fragments? android android

How to implement onBackPressed() in Fragments?


I solved in this way override onBackPressed in the Activity. All the FragmentTransaction are addToBackStack before commit:

@Overridepublic void onBackPressed() {    int count = getSupportFragmentManager().getBackStackEntryCount();    if (count == 0) {        super.onBackPressed();        //additional code    } else {        getSupportFragmentManager().popBackStack();    }}


In my opinion the best solution is:

JAVA SOLUTION

Create simple interface :

public interface IOnBackPressed {    /**     * If you return true the back press will not be taken into account, otherwise the activity will act naturally     * @return true if your processing has priority if not false     */    boolean onBackPressed();}

And in your Activity

public class MyActivity extends Activity {    @Override public void onBackPressed() {    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_container);       if (!(fragment instanceof IOnBackPressed) || !((IOnBackPressed) fragment).onBackPressed()) {          super.onBackPressed();       }    } ...}

Finally in your Fragment:

public class MyFragment extends Fragment implements IOnBackPressed{   @Override   public boolean onBackPressed() {       if (myCondition) {            //action not popBackStack            return true;         } else {            return false;        }    }}

KOTLIN SOLUTION

1 - Create Interface

interface IOnBackPressed {    fun onBackPressed(): Boolean}

2 - Prepare your Activity

class MyActivity : AppCompatActivity() {    override fun onBackPressed() {        val fragment =            this.supportFragmentManager.findFragmentById(R.id.main_container)        (fragment as? IOnBackPressed)?.onBackPressed()?.not()?.let {            super.onBackPressed()        }    }}

3 - Implement in your target Fragment

class MyFragment : Fragment(), IOnBackPressed {    override fun onBackPressed(): Boolean {        return if (myCondition) {            //action not popBackStack            true        } else {            false        }    }}


If you're using androidx.appcompat:appcompat:1.1.0 or above then you can add an OnBackPressedCallback to your fragment as follows

requireActivity()    .onBackPressedDispatcher    .addCallback(this, object : OnBackPressedCallback(true) {        override fun handleOnBackPressed() {            Log.d(TAG, "Fragment back pressed invoked")            // Do custom work here                // if you want onBackPressed() to be called as normal afterwards            if (isEnabled) {                isEnabled = false                requireActivity().onBackPressed()            }        }    })

See https://developer.android.com/guide/navigation/navigation-custom-back