I'm building a simple app and I want to go back from fragment to activity with physical button. How do I do that? I have tried to kill the fragment but it isn't working.
Calling addToBackStack() commits the transaction to the back stack. The user can later reverse the transaction and bring back the previous fragment by pressing the Back button. If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.
As Fragment is embedded inside an Activity, it will be killed when Activity is killed.
You can get a reference to the FragmentActivity by calling getActivity() on your current Fragment and then call from the Activity retrieved onBackPressed() method.
getActivity().onBackPressed();
I do it like this and it's working very fine.
Start fragment:
public void showMyFragment(View V){
Fragment fragment = null;
fragment = new MyFragment();
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).addToBackStack(null).commit();
}
}
This is how to end fragment with back button:
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
this.finish();
} else {
getFragmentManager().popBackStack();
}
}
Your Fragment:
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.activity_info, null);
return v;
}
}
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