Why Dialog does not have a NavController [Missing]

2019-08-29 16:33发布

问题:

I am trying to use the latest update of Nav Component in my application

where i can add dialog(BottomSheetDialogFragment) in my nav graph

nav_version = "2.1.0-alpha05"

Part of code from my nav_graph:

    <dialog
        android:id="@+id/settingFragment"
        android:name="com.andor.navigate.notepad.listing.fragment.SettingFragment"
        tools:layout="@layout/fragment_setting">
        <action
            android:id="@+id/action_settingFragment_to_confirmationFragment"
            app:destination="@id/confirmationFragment" />
    </dialog>
    <dialog
        android:id="@+id/confirmationFragment"
        android:name="com.andor.navigate.notepad.ConfirmationFragment"
        tools:layout="@layout/fragment_confirmation" />

In my Setting's Fragment i have a button(logout_btn) to trigger the action: action_settingFragment_to_confirmationFragment

code in OnActivityCreated of the Setting's fragment:

    logout_btn.setOnClickListener {
       Navigation.findNavController(view!!).navigate(R.id.action_settingFragment_to_confirmationFragment)
    } 

When i Click on the button there is a runtime Exception:

java.lang.IllegalStateException: View androidx.constraintlayout.widget.ConstraintLayout{550ae09 V.E...... ........ 1,1-719,526} does not have a NavController set at androidx.navigation.Navigation.findNavController(Navigation.java:84) at com.andor.navigate.notepad.listing.fragment.SettingFragment$onActivityCreated$2.onClick(SettingFragment.kt:56) at android.view.View.performClick(View.java:7352) at android.view.View.performClickInternal(View.java:7318) at android.view.View.access$3200(View.java:846) at android.view.View$PerformClick.run(View.java:27800) at android.os.Handler.handleCallback(Handler.java:873) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7045) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)

My aim is to open a dialog from another dialog, but for some reason my dialog is not having(missing) NavController.

I have already referred to the source code

回答1:

A DialogFragment operates in an entirely separate window which is not in the same view hierarchy as your NavController.

You should use NavHostFragment.findNavController(this) (where this is your DialogFragment)) or the Kotlin extension findNavController() if you are using the fragment-ktx dependency which walks up the fragment hierarchy to find your NavController.