Android Jetpack导航如何处理工具栏和BottomNavBar内容 [英] Android Jetpack Navigation How to handle the Toolbar and BottomNavBar content

本文介绍了Android Jetpack导航如何处理工具栏和BottomNavBar内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对导航组件如何适应应用程序行为感到有些困惑.在教程中,您所做的事情并不会太复杂,但是在实际应用中实施时,情况似乎有所不同.

I am a bit confused on how the Navigation component fits in the app behavior. It all looks nice and shiny in tutorials where you don't do things too complex but when implementing in real app, things seem different.

导航之前

在实施导航之前,我必须手动运行片段事务.为了做到这一点,我的片段将实现接口 onFragmentAction ,该接口将 bundle 传递给主 Activity ,并基于动作在活动中,将当前片段替换为另一个片段.

Before implementing navigation I had to manually run fragment transactions. In order to do this, my fragment would implement an interface onFragmentAction which passed a bundle to the main Activity and in the activity based on the actions, replace the current fragment with another one.

需要处理的第二部分是顶部工具栏和 BottomAppBar .例如, BottomAppBar 需要使 FAB 在某些片段上不同地对齐或在其他片段中隐藏.另外,顶部的 ToolBar 需要在某些位置扩展或在其他位置折叠.为此,我听了 FragmentManager.OnBackStackChangedListener 并基于片段标签 getSupportFragmentManager().getBackStackEntryAt(size-1).getName()相应地更改布局.

The second part that needs handling is the top toolbar and the BottomAppBar. For instance BottomAppBar needs to have the FAB aligned differently on some fragments or hidden in others. Also the top ToolBar needs to be expanded on some or collapsed on others. To do this, I listened to FragmentManager.OnBackStackChangedListener and based on the fragment tag getSupportFragmentManager().getBackStackEntryAt(size - 1).getName() change the layout accordingly.

具有导航功能

第一部分似乎很容易做到:传递参数并开始新的片段.但是我不知道导航是否可以处理工具栏管理,或者我需要继续从活动"中进行管理.

The first part seems to be easy to do: pass params and start new fragments. But I have no idea if navigation can handle the toolbars management or I need to keep managing it from my Activity.

推荐答案

工具栏标题是基于导航图中的标签"值设置的,如果您想对工具栏或BottomAppBar进行其他操作,则可以在活动中添加addOnNavigatedListener,并根据当前目的地进行操作.

The toolbar title is set based on 'label' value inside navigation graph, if you want to do something different with toolbar or BottomAppBar you can add addOnNavigatedListener inside your activity, and based on current destination do something.

findNavController(nav_host_fragment).addOnNavigatedListener { controller, 
 destination ->
 when(destination.id) {
    R.id.destination1 -> {
        //Do something with your toolbar or BottomAppBar
    }
    R.id.destination2 -> {
        //Do something with your toolbar or BottomAppBar
    }

 }
}

这篇关于Android Jetpack导航如何处理工具栏和BottomNavBar内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆