Currently, my main activity has a description field which opens a fragment when the user clicks on the description. On the fragment there is a text field and a button, when I click the button, I want to close the fragment and go back to my activity.
How can I achieve this?
I have added an onClickListener to my fragment to capture the click on the button. The toast message gets printed, but the fragment is not removed/closed.
descDismiss.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(), "Dismissed", Toast.LENGTH_LONG).show();
getActivity().getFragmentManager().popBackStackImmediate();
}
});
I have the onClickListener in the onCreateView of the fragment. Is this correct?
Thanks in advance!
I am adding my fragment like this:
((MainActivity)context).getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, frag).commit();
try this first add the fragment to backstack like this
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(..............);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Then remove the fragment like this:-
FragmentManager fm = getActivity().getSupportFragmentManager();
if(fm.getBackStackEntryCount()>0) {
fm.popBackStack();
}
to remove all fragments
FragmentManager fm = getActivity().getSupportFragmentManager();
for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
try this
getActivity().getSupportFragmentManager().popBackStack();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With