首页 > 解决方案 > 从包含 DialogFragment 的片段向上导航正在重新显示 DialogFragment 导航组件

问题描述

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

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

当用户单击 menuitem 时,将显示该对话框,如下所示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再次显示

标签: androidandroid-jetpackandroid-architecture-navigationandroid-jetpack-navigation

解决方案


经过长时间的搜索,返回箭头也被认为是一个菜单项

因此,当单击后退箭头时,将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)
}

推荐阅读