1、使用 NavigationUI 更新界面组件
Navigation 组件包含 NavigationUI
类。此类包含使用顶部应用栏、抽屉式导航栏和底部导航栏管理导航的静态方法。
可参阅:
Android Material 常用组件详解(七)—— BottomNavigationView 使用详解
Android Material 常用组件详解(九)—— NavigationView 使用详解
Android Material 常用组件详解(十)—— ToolBar、AppBarLayout、CoordinatorLayout、CollapsingToolbarLayout 使用详解
1.1 顶部应用栏
顶部应用栏在应用顶部提供了一个固定位置,用于显示当前屏幕的信息和操作。如需详细了解应用栏,请参阅设置应用栏。
NavigationUI
包含在用户浏览您的应用时自动更新顶部应用栏中内容的方法。例如,NavigationUI 使用导航图中的目的地标签android:label
及时更新顶部应用栏的标题,即应用栏的标题会显示与之对应的android:label
内容。
<navigation>
<fragment ...
android:label="Page title">
...
</fragment>
</navigation>
NavigationUI 支持以下顶部应用栏类型:
- Toolbar
- CollapsingToolbarLayout
- ActionBar
Toolbar
NavigationUI 使用 AppBarConfiguration
对象管理在应用显示区域左上角的导航按钮行为。导航按钮的行为会根据用户是否位于顶级目的地而变化。
当用户位于顶级目的地时,如果目的地使用 DrawerLayout,导航按钮会变为抽屉式导航栏图标 。如果目的地没有使用 DrawerLayout,导航按钮处于隐藏状态。当用户位于任何其他目的地上时,导航按钮会显示为向上按钮
。
<LinearLayout>
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar" />
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
... />
...
</LinearLayout>
val navController = findNavController(R.id.nav_host_fragment)
val appBarConfiguration = AppBarConfiguration(navController.graph)
// val appBarConfiguration = AppBarConfiguration(setOf( R.id.fragmentA, R.id.fragmentB, R.id.fragmentC))
toolbar.setupWithNavController(navController, appBarConfiguration)
CollapsingToolbarLayout
<LinearLayout>
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="@dimen/tall_toolbar_height">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleGravity="top"
app:layout_scrollFlags="scroll|exitUntilCollapsed|snap">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"/>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
... />
...
</LinearLayout>
override fun onCreate(savedInstanceState: Bundle?) {
setContentView(R.layout.activity_main)
val layout = findViewById<CollapsingToolbarLayout>(R.id.collapsing_toolbar_layout)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
val navController = findNavController(R.id.nav_host_fragment)
val appBarConfiguration = AppBarConfiguration(navController.graph)
layout.setupWithNavController(toolbar, navController, appBarConfiguration)
}
默认应用栏
如需向默认操作栏添加导航支持,请通过主 Activity 的 onCreate()
方法调用 setupActionBarWithNavController()
,如下所示。请注意,您需要在 onCreate() 之外声明 AppBarConfiguration,因为您在替换 onSupportNavigateUp() 时也使用该方法: