且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何正确实现导航抽屉中顶部的后退按钮?

更新时间:2022-05-21 17:07:45

if (item.getItemId() == android.R.id.home) {
    int backStackCount = fragmentManager.getBackStackEntryCount();//check currently how many frags loaded
    if (backStackCount > 0) {
        fragmentManager.popBackStack(); //go back to previously loaded fragment
    }   
}

当前,单击"上一步"仅退出应用程序。

使用popBackStack()将弹出使您的应用程序存在的后栈,但您只需返回到默认片段。

要解决此问题,您需要更改抽屉汉堡按钮的行为,以便有时可以使用它打开抽屉的navView布局,有时可以使用它返回到默认片段;后者是在您要添加顶部的后退按钮时使用的。

如何实现导航抽屉的上/上后退按钮

这需要访问使您能够将侦听器添加到汉堡点击的setToolbarNavigationClickListener方法。

在这种情况下,您需要在onCreate()方法Add:

中根据需要返回到Home片段
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Enable the functionality of opening the side drawer, when the burger icon is clicked
        toggle.setDrawerIndicatorEnabled(true); // Show the burger icon & enable the drawer funcionality
        navController.navigate(R.id.home); // Back to default fragment (replace home with your default fragment id in the navGraph)
    }
});

剩下的部分是在您想要转到某个片段时显示后退按钮

并使用toggle.setDrawerIndicatorEnabled()启用/禁用单击主页/汉堡图标时打开/关闭抽屉的功能

navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
    @Override
    public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {

        // Repeat this condition for all the Fragments that you want to show the back button
        if (destination.getId() == R.id.settings_id) { // replace `settings_id` with your fragment id in the navGraph that you want to show the back button
            // Disable the functionality of opening the side drawer, when the burger icon is clicked & show the UP button instead
            toggle.setDrawerIndicatorEnabled(false);

        } 

    }
});