Fragment与activity通信,DialogFragment与Fragment通信可以使用ViewModel来实现
1、Fragment中使用activity的ViewModel
private val homeMainViewModel: HomeMainSharedViewModel by activityViewModels()
2、DialogFragment中使用Fragment的ViewModel
需要注意DialogFragment的创建方式,使用childFragmentManager来创建
fun createDialog(){
childFragmentManager.apply {
val musicShowComfortModeDialog = MusicShowComfortModeDialog()
musicShowComfortModeDialog.showNow(this, MUSIC_SHOW_COMFORT_MODE_DIALOG)
}
}
fun showNow(manager: FragmentManager, tag: String?) {
val ft = manager.beginTransaction()
ft.add(this, tag)
ft.commitNowAllowingStateLoss()
}
然后在DialogFragment中就可以直接使用父Fragment的ViewModel了
private val musicShowViewModel: MusicShowViewModel by viewModels({ requireParentFragment() })
3、Activity或者Fragment创建自己的ViewModel的方式
其中application,SoundModel,CarAdaptAPI为HomeMainSharedViewModel构造函数中所必须的参数
private val viewModel by viewModels<HomeMainSharedViewModel> {
createViewModelFactory(
HomeMainSharedViewModel::class.java,
application,
SoundModel,
CarAdaptAPI
)
}
class HomeMainSharedViewModel(
app: Application,
private val soundModel: SoundModel,
private val carAdaptAPI: CarAdaptAPI
) : ViewModel() {}