Search code examples
androidandroid-fragmentsandroid-viewpageronbackpressed

android prevent fragment leave on back pressed


I have a ViewPager inside a FragmentActivity. For each page I have a Fragment with an EditText.

I want to prevent the user leaving the screen if the EditText value has changed, showing a warning Dialog asking if he/she really wants to leave the screen.

For that I need to check the EditText value when the back Button is pressed.

I have only found how to do it but using the onBackPressed() method in the container FragmentActivity.

The problem is that I don't know how to access the EditText inside the Fragment from the parent FragmentActivity.

Is it not possible just to do it in the Fragment? I've tried the method onStop and onDetach but they are called after leaving the Fragment, so I cannot stop it.

Any ideas?


Solution

  • Try this in your parent Activity:

    @Override
    public void onBackPressed() {
         super.onBackPressed();
    
         YourFragment fragment = (YourFragment) getSupportFragmentManager().getFragments().get(viewPager.getCurrentItem());
    
    }
    

    Then you have access to your Fragment so you can add a parameter in your fragment textHasChanged (for example) and update it when the text changes.