Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

android - How to set target fragment of a dialog when using navigation components

I'm showing a dialog inside a fragment using childFragmentManager or within an Activity using the supportFragmentManager, in the process I would like to set the target fragment, like this:

val textSearchDialog = TextSearchDialogFragment.newInstance()
textSearchDialog.setTargetFragment(PlaceSearchFragment@this, 0)

But when running that code I get the error:

java.lang.IllegalStateException: Fragment TextSearchDialogFragment{b7fce67 #0 0} declared target fragment PlaceSearchFragment{f87414 #0 id=0x7f080078} that does not belong to this FragmentManager!

I don't know how to access the FragmentManager the navigation components are using to manage the showing of the fragment, is there a solution for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update: as part of Navigation 2.3.0, Navigation adds explicit support for returning a result with a specific section on returning a result from a Dialog destination as an alternative to using a shared ViewModel.

Previous answer:

The recommended pattern for communicating between Fragments with the Navigation Architecture Components is via a shared ViewModel - a ViewModel that lives at the Activity level achieved by retrieving the ViewModel using ViewModelProvider(getActivity())

As per the documentation, this offers a number of benefits:

  • The activity does not need to do anything, or know anything about this communication.
  • Fragments don't need to know about each other besides the SharedViewModel contract. If one of the fragments disappears, the other one keeps working as usual.
  • Each fragment has its own lifecycle, and is not affected by the lifecycle of the other one. If one fragment replaces the other one, the UI continues to work without any problems.

You can also share ViewModels at a smaller scope than your whole activity by using a navigation graph scoped ViewModel.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...