Close a fragment on button click which is inside that fragment

The solution from oskarko work but it brings you back to the main Activity.

If you want your fragment to close from inside your Fragment and you don't want to leave the current Activity, try this approach:

getFragmentManager().beginTransaction().remove(ActivityFragment.this).commit(); 

Where "ActivityFragment" is the name of your Fragment.

Consider this: If you add your FragmentManager adds the Fragment to the backStack (fragmentTransaction.addToBackStack(null);), you should not use this approach, instead use:

getFragmentManager().popBackStack(); 

The Reason for this is if you close it with the first method, your Fragment is still in the backStack and you have to click the Previous Button twice to get to the previous Activity.


Just call:

getActivity().onBackPressed();