简体   繁体   中英

How to customise up navigation in android?

Instead of having up navigation in the action bar return to its parent activity, I would like to have it return to the last fragment or just be able to alter its behaviour and appearence.

How can this be achieved?

You can try this: nothing that the up navigation is like any other menu item except it is special as far as the id is concerned:

Let me add a few more code to demo how to change icon:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

assert toolbar != null;
toolbar.setNavigationIcon(R.drawable.close);

Handling Fragments Popping:

//when adding your fragment to the activity, add it to back stack like this
fragmentTransaction.addToBackStack("frag1");

//inside onOptionsItemSelected(MenuItem item)
switch(item.getId()){
   case android.R.id.home:
   FragmentManager fm = getActivity().getSupportFragmentManager();
   fm.popBackStack ("frag1", FragmentManager.POP_BACK_STACK_INCLUSIVE);
   return true;
}

You can remove a fragment from the back stack

You can also alter the icon by setting a different resource inside your onCreate!

UPDATE

Since a fragment always lives inside an Activity, you wouldn't have to change a thing in your fragment but if you want a fragment to have more menu items like on the right hand side, you can enable optionsMenu inside onCreate() like this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setHasOptionsMenu(true);

}

From here, you can do as you would normally do in your activity!

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM