Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

android - How to share the same ViewModel with ViewPager, Navigation and Hilt?

I'm trying to use the same ViewHolder between this fragments.

FragmentA, FragmentB and Fragment E are in a navGraph, Fragment C and D are not.

I tried using by viewModels() but it initialized the ViewModel 3 times (on A, C, E)

Using by activityViewModels() it initilized the ViewModel 2 times (on A and C)

I also tried by viewModels(ownerProducer = {requireParentFragment().requireParentFragment()}) in Fragment C and D but it keeps initializing the ViewModel.

And the last thing i tried is inserting Fragment A, B and E into a navGraph and using by navGraphViewModels(R.id.customNavGraph) { defaultViewModelProviderFactory } but got the same result as above.

In conclusion, Fragment C and D keep initializing the ViewModel

How can i fix this?

enter image description here


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

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...