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.
Asked
Active
Viewed 2.4k times
7
-
You can save state of fragment [like this][1] [1]: http://stackoverflow.com/questions/11353075/how-can-i-maintain-fragment-state-when-added-to-the-back-stack – R World Aug 30 '14 at 20:24
2 Answers
14
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();
Víctor Albertos
- 7,715
- 5
- 39
- 68
12
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;
}
}
MilanNz
- 1,290
- 3
- 12
- 28