Issue
I am trying to show dialog using navigation component in android. I have gone through the other question asked at stackoverflow Navigation Architecture Component - Dialog Fragments
I have added dialog component in nav_graph.xml
as below
<dialog
android:id="@+id/dialog"
android:name="com.android.example.ui.MyDialogFragment"
tools:layout="@layout/dialog_fragment" />
I have added an action in my other fragment to show the dialog as below in nav_graph.xml
<fragment
android:id="@+id/Fragment1"
android:name="com.android.example.ui.Fragment1"
android:label="Fragment"
tools:layout="@layout/fragment1">
<action
android:id="@+id/action_fragment1_to_dialog"
app:destination="@id/dialog" />
</fragment>
I have created a kotlin
class MyDialogFragment
as below
class MyDialogFragment : DialogFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(
R.layout.dialog_fragment,
container, false
)
}
}
Here from Fragment1
class, I am trying to show dialog as below
findNavController().navigate(R.id.action_fragment1_to_dialog)
when I try to show the dialog, I get the below error
Preblem 1 is Solved
java.lang.ClassCastException: androidx.navigation.fragment.DialogFragmentNavigator$Destination cannot be cast to androidx.navigation.fragment.FragmentNavigator$Destination
at com.android.dairy.MainActivity$onCreate$1.onDestinationChanged(MainActivity.kt:47)
at androidx.navigation.NavController.dispatchOnDestinationChanged(NavController.java:504)
at androidx.navigation.NavController.navigate(NavController.java:1142)
at androidx.navigation.NavController.navigate(NavController.java:944)
at androidx.navigation.NavController.navigate(NavController.java:877)
at androidx.navigation.NavController.navigate(NavController.java:863)
at androidx.navigation.NavController.navigate(NavController.java:851)
Problem2
How can I get the instance of MyDialogFragment to update its properties or setup the button onClick
listener in Fragment1
Solution
Your first problem says:
java.lang.ClassCastException: androidx.navigation.fragment.DialogFragmentNavigator$Destination
cannot be cast to androidx.navigation.fragment.FragmentNavigator$Destination
at com.android.dairy.MainActivity$onCreate$1.onDestinationChanged(MainActivity.kt:47)
So your issue is that your onDestinationChanged
callback in your MainActivity
is incorrectly casting your type of destination. You need to change your code to avoid that.
Your second problem is about returning a result from your dialog. The documentation covers returning a result and even has a section specifically around Additional considerations when using DialogFragments (namely, that the Fragment
's Lifecycle isn't affected by a dialog, so this is one case where using the NavBackStackEntry
's Lifecycle can specifically help you).
Answered By - ianhanniballake
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.