我正在尝试注入活动的视图模型,并且想在Dialog Fragment中使用它,如何用Kodein注入它?并使用我之前在其他活动或片段中注入的视图模型。
我已经尝试过中等水平的教程,这是教程
https://proandroiddev.com/android-viewmodel-dependency-injection-with-kodein-249f80f083c9
我正在尝试从活动的视图模型访问注入结果 但是当我尝试从Dialog Fragment访问viewModel内部的某些对象时,该值为null与活动的viewModel不相同
// This is from Activity
private val viewModelFactory: TriplogisticViewModelFactory by instance()
private val viewModel: TriplogisticViewModel by lazy {
ViewModelProviders
.of(this@ContactDetailBottomSheetDialogFragment, viewModelFactory)
.get(TriplogisticViewModel::class.java)
}
Log.e("VIEWMODEL_ACTIVITY", viewModel.mode.get().toString) // result is SENDER_MODE
我期望当我访问对话框片段的viewModel中的某个对象时,我得到的值与活动的viewModel相同
// This is from Dialog Fragment
private val viewModelFactory: TriplogisticViewModelFactory by instance()
private val viewModel: TriplogisticViewModel by lazy {
ViewModelProviders
.of(this@ContactDetailBottomSheetDialogFragment, viewModelFactory)
.get(TriplogisticViewModel::class.java)
}
我想要与活动的viewModel对象相同的结果,但结果为空
Log.e("VIEWMODEL_FRAGMENT", viewModel.mode.get().toString) // result is null
答案 0 :(得分:0)
您必须使用共享的ViewModel
。使用活动所有者实例化ViewModel
。看起来像:
class SharedViewModel : ViewModel() {
val selected = MutableLiveData<Item>()
fun select(item: Item) {
selected.value = item
}
}
class MasterFragment : Fragment() {
private lateinit var itemSelector: Selector
private lateinit var model: SharedViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
model = activity?.run {
ViewModelProviders.of(this)[SharedViewModel::class.java]
} ?: throw Exception("Invalid Activity")
itemSelector.setOnClickListener { item ->
// Update the UI
}
}
}
class DetailFragment : Fragment() {
private lateinit var model: SharedViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
model = activity?.run {
ViewModelProviders.of(this)[SharedViewModel::class.java]
} ?: throw Exception("Invalid Activity")
model.selected.observe(this, Observer<Item> { item ->
// Update the UI
})
}
}
有关详细信息,请单击here