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

Ali Habbash :

I'm using navigation component and I have setup the up arrow to handle automatically the navigation process in my only activity mainActivity I have this:

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

the dialog is shown when the user is click on the menuitem from StationsFragment like this:

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
}

and, I have setup the navigation graph like this:

<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" />

Here, in the image i'm in the StationFragment and I have the info menuItem

enter image description here

and when I click on info menuItem the dialog is shown normally

enter image description here

and when I dismiss the dialog and click on up arrow of the StationsFragment the dialog is shown again

Ali Habbash :

After long searching, that the back arrow is also considered a menu item

so, when back arrow is clicked the onOptionsItemSelected method is called and it's need to check for menu item id.

and the code will be :

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)
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=345938&siteId=1