Search code examples
androidandroid-activityandroid-fragments

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.


Solution

  • 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;
                }
            }