Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get back to previous activity from a fragment

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.

like image 907
MilanNz Avatar asked Aug 30 '14 20:08

MilanNz


People also ask

How do you ensure that the user can return to the previous fragment by pressing the back button?

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.

What happens to fragment when activity is destroyed?

As Fragment is embedded inside an Activity, it will be killed when Activity is killed.


2 Answers

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();
like image 70
Víctor Albertos Avatar answered Sep 21 '22 09:09

Víctor Albertos


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;
            }
        }
like image 27
MilanNz Avatar answered Sep 25 '22 09:09

MilanNz