简体   繁体   English

如何在Android中自定义导航?

[英]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: 您可以尝试以下操作:向上导航与其他任何菜单项都一样,唯一不同的是,就ID而言,它是特殊的:

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! 您还可以通过在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: 由于片段始终位于Activity中,因此您无需更改片段中的任何内容,但是如果您希望片段具有更多菜单项(如右侧),则可以在onCreate()中启用optionsMenu,如下所示:

@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! 我希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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