Android fragment back button event detection?

Asked 2 years ago, Updated 2 years ago, 68 views

From the fragment now

Opening another fragment with addToBackStack(null);

Pressing the back button in this state returns you to the original fragment

What I want to do is addToBackStack(null); When I open another fragment, if I press the back button, the opened fragment closes

Return to main fragment

If I press the back button on the main fragment, I want to do something else (For example, float a dialog.)

What should I do to do this?

Thank you^

^

android fragment

2022-09-22 13:46

2 Answers

If you don't have to stack the back key when you return to the Main Fragment, you can override onBackPressed() in Activity to handle the desired action.

override fun onBackPressed() {
     super.onBackPressed()
     //do something
}


2022-09-22 13:46

Good idea.

First, create OnBackPressedListener interface.

public interface OnBackPressedListener {
    void onBackPressed();
}

And interface for each Fragment do implementations. For example, below.

public class SettingFragment extends Fragment 
implements OnBackPressedListner {
    @Override
    void onBackPressed() {
        // // doIt your code
    }
}

And if you override the onBackPressed() of the parent Activity as follows,

@Override
public void onBackPressed() {
    List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
    if (fragmentList != null) {
        //TODO: Perform your logic to pass back press here
        for(Fragment fragment : fragmentList){
           if(fragment instanceof OnBackPressedListener){
               ((OnBackPressedListener)fragment).onBackPressed();
           }
        }
    }
}

For each Fragment, the desired BackButton action is possible.


2022-09-22 13:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.