使用导航视图和工具栏不显示后退按钮

Back button not displaying using navigation view and toolbar

我有一个具有以下层次结构的应用程序:

MainActivity (Shows list of dates) 
    | 
ViewPagerFragment (Shows list of children for those dates)
    | 
ChildFragment (Detail View)

我正在尝试从设计支持库中实现导航视图,但无法使工具栏上的实际导航正常工作。

这是主 Activity 工具栏:

这是从主 activity 导航到那里后的 ViewPagerFragment,请注意没有后退按钮...

这是所需的工具栏:

我正在使用以下代码添加片段:

    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.content_frame, fragment, fragment.getClass().getName())
            .addToBackStack(fragment.getClass().getName())
            .commitAllowingStateLoss();

这里是activity启动相关的代码:

protected void setupActionBar() {
    setSupportActionBar(toolbar);

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

我的导航抽屉设置:

protected void setupNavigationDrawer() {
    navigationView.setNavigationItemSelectedListener(this);
    actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawerLayout.setDrawerListener(actionBarDrawerToggle);
    actionBarDrawerToggle.syncState();
}

点击设备上的硬件后退按钮可以正确返回。我似乎无法让后退箭头显示在抽屉开关上...有什么建议吗?

您是否尝试访问 Activity 的 ActionBar?

在 onViewCreated 中:

Toolbar mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
((Activity) getActivity()).setSupportActionBar(mToolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

要禁用导航抽屉图标并显示不同的图标,您需要在 ActionBarDrawerToggle 上调用 setDrawerIndicatorEnabled(false)

您可能还需要调用 setHomeAsUpIndicator() 来指定要使用的图标而不是 "hamburger" 图标。