使用带有两个导航图的Android导航处理后退按钮

时间:2019-01-17 21:20:16

标签: android android-navigation android-bottom-nav-view

我创建了一个小样本应用程序来测试android导航库。总体思路是,我想要两个带有自己的导航图的标签。

我的主要活动布局包含一个BottomNavigationView和两个NavHost

ButtonNavigationView单击侦听器负责显示一个NavHost或另一个NavigationUI.setupActionBarWithNavController,并使用选定的控制器调用app:defaultNavHost="true"来相应地更新工具栏。向上导航正常。

我现在面临的问题是后退按钮。

有一个属性NavHostFragment,可确保您的onBackPressed()截获系统后退按钮,但我希​​望根据活动图形将其打开/关闭。我找不到改变它的方法:(

我知道我可以覆盖import { Injectable } from '@angular/core'; import { NavigationEnd, Router } from '@angular/router'; import { filter } from 'rxjs/operators'; @Injectable() export class RouteInterceptorService { private _previousUrl: string; private _currentUrl: string; private _routeHistory: string[]; constructor(router: Router) { this._routeHistory = []; router.events .pipe(filter(event => event instanceof NavigationEnd)) .subscribe((event: NavigationEnd) => { this._setURLs(event); }); } private _setURLs(event: NavigationEnd): void { const tempUrl = this._currentUrl; this._previousUrl = tempUrl; this._currentUrl = event.urlAfterRedirects; this._routeHistory.push(event.urlAfterRedirects); } get previousUrl(): string { return this._previousUrl; } get currentUrl(): string { return this._currentUrl; } get routeHistory(): string[] { return this._routeHistory; } } ,但我正在尝试为图书馆找到一种方法,让我知道哪个图形处于活动状态。

1 个答案:

答案 0 :(得分:3)

根据NavHostFragment sourceapp:defaultNavHost="true"所做的只是调用setPrimaryNavigationFragment(),这就是FragmentManager知道向哪个子Fragment发送回退按钮事件的方式。

因此,当切换到新的Fragment时,可以将setPrimaryNavigationFragment()添加到FragmentTransaction中以获得相同的行为。