从包含 DialogFragment 的片段向上导航正在重新显示 DialogFragment 导航组件

Navigate up from fragment that contains DialogFragment is re-showing the DialogFragment navigation component

我正在使用导航组件,我已经设置了向上箭头来自动处理我唯一的导航过程 activity mainActivity 我有这个:

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return item.onNavDestinationSelected(navController) || super.onOptionsItemSelected(item)
}

当用户单击 StationsFragment 中的菜单项时会显示对话框,如下所示:

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    val bundle = Bundle()
    bundle.putInt(GAME_ID_BUNDLE_KEY, gameId)
    findNavController().navigate(R.id.action_stationsFragment_to_gameInfoDialog, bundle)
    return true
}

并且,我设置了这样的导航图:

<fragment
    android:id="@+id/stationsFragment"
    android:name="com.accad.accadgame.screens.fragments.StationsFragment"
    android:label="@string/stations_fragment_title"
    tools:layout="@layout/fragment_stations"
    >
    <argument
        android:name="game_id"
        app:argType="integer"
        android:defaultValue="-1" />
    <action
        android:id="@+id/action_stationsFragment_to_sectionsFragment"
        app:destination="@id/sectionsFragment"
        app:popUpTo="@+id/stationsFragment"
        app:popUpToInclusive="false" />
    <action
        android:id="@+id/action_stationsFragment_to_gameInfoDialog"
        app:destination="@id/gameInfoDialog"
        app:popUpTo="@id/stationsFragment"
        app:popUpToInclusive="false"
        />
</fragment>
<dialog
    android:id="@+id/gameInfoDialog"
    android:name="com.accad.accadgame.screens.dialogs.GameInfoDialog"
    android:label="GameInfoDialog"
    tools:layout="@layout/dialog_game_info"
    >
    <argument
        android:name="game_id"
        app:argType="integer"
        android:defaultValue="-1" />

在这里,在图像中我在 StationFragment 并且我有 info menuItem

当我单击 info menuItem 时,对话框正常显示

当我关闭对话框并单击 StationsFragment 的向上箭头时,对话框再次显示

找了半天发现后退箭头也算菜单项

因此,当单击后退箭头时,将调用 onOptionsItemSelected 方法,它需要检查菜单项 ID。

代码为:

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    if(item.itemId == R.id.gameInfo) {
        val bundle = Bundle()
        bundle.putInt(GAME_ID_BUNDLE_KEY, gameId)
        findNavController().navigate(R.id.action_stationsFragment_to_gameInfoDialog, bundle)
        return true
    }
    return super.onOptionsItemSelected(item)
}