Apply onBackPressed in a fragment

1

How to apply onBackPressed() in a fragment ?

It does not work the same as in an activity, then I explain exactly my case:

I need to be in my fragment when I press the "back" button that all the android files bring by default, this redirects to another fragment

    
asked by ERny JOsé HIdalgo COrrea 22.01.2017 в 23:17
source

4 answers

1

If you use a FragmentManager , the answer is very simple. Just add .addToBackStack(tag) to your transaction. Example:

    getFragmentManager().beginTransaction()
            .replace(R.id.container, MainFragment.newInstance(),"main").addToBackStack("main")
            .commit();
    
answered by 22.01.2017 в 23:39
1

I show you an example of how I did it:

This goes when you are going to open a fragment:

....replace(R.id.container, new ChatView()).addToBackStack(null)
                        .commit(); 

Within your fragment you place the onBackPressed() method

@Override
    public void onBackPressed() {

        int count = getFragmentManager().getBackStackEntryCount();

        if (count == 0) {
            super.onBackPressed();
            getFragmentManager().popBackStack();
        } else {
            getFragmentManager().popBackStack();
        }

    }
    
answered by 23.01.2017 в 17:08
0

Regularly who determines the transaction of Fragments is the Activity, the simplest option is to call the onBackPressed() of the Activity that contains the Fragment :

getActivity().onBackPressed();

and in the onBackPressed() of the Activity method you obtain the Fragment that was added to the BackStack.

@Override
public void onBackPressed() 
{
  if(getFragmentManager().getBackStackEntryCount() > 0)
    getFragmentManager().popBackStack();
  else
   super.onBackPressed();
}

For this to work, remember to add the fragments to the BackStack with addToBackStack() :

fragmentManager.beginTransaction().replace(R.id.home_container, frag).addToBackStack(null).commit();
    
answered by 23.01.2017 в 17:53
0

I do not understand your question well, if what you want is that when you give it back to the previous fragment add this fragment of code when you create the fragment.

NombreDeTuFragmentManager.popBackStack();
    
answered by 07.01.2018 в 20:43