【问题标题】:Navigate up from fragment that contains DialogFragment is re-showing the DialogFragment navigation component从包含 DialogFragment 的片段向上导航正在重新显示 DialogFragment 导航组件
【发布时间】:2020-03-12 00:16:08
【问题描述】:

我正在使用导航组件,并且我已经设置了向上箭头以在我唯一的活动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 的向上箭头时,对话框再次显示

【问题讨论】:

    标签: android android-jetpack android-architecture-navigation android-jetpack-navigation


    【解决方案1】:

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

    所以,当点击返回箭头时,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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 2020-09-12
      • 2019-12-07
      • 1970-01-01
      相关资源
      最近更新 更多