How to add "UP" back button in fragment (Fragment to Activity)

Viewed 17957

I want to go from fragment to activity using back button using toolbar back icon.

like this one

The fragment is my navigation drawer item & activity is my MainActivity.

How do I do it?

6 Answers

Try this worked for me :

  1. in XML:

    <android.support.v7.widget.Toolbar
     android:id="@+id/profileToolbar"
     android:layout_width="match_parent"
     android:layout_height="wrap_content">
    
  2. Create an back arrow icon in drawable folder. Name it 'ic_back_button'. Not sure how :-
    just right click on drawable > new > ImageAsset > Clip Art > Search back > select > OK > Finish (don't forget to change the name).

  3. then Inside your fragment in onCreateView :

        Toolbar toolbar = view.findViewById(R.id.profileToolbar);
        toolbar.setNavigationIcon(R.drawable.ic_back_button);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          getActivity().onBackPressed();
        }
        });
    

It might help in case if you want to come back from fragment to previous location.

Put this in your class with navController.

  @Override
public boolean onSupportNavigateUp() {
    navController.navigateUp();
    return super.onSupportNavigateUp();
}

don't forget implement relevant dependency such as navigation and navigation UI.

You can easily do that, if you are using a Custom back button that is placed on your Custom top app bar, in the button's onClick() function you can call.. getActivity().onBackPressed(); it would work the same as if you have clicked the android navigation's back button...

Related