0

我正在尝试注入活动的视图模型,我想在对话框片段中使用它,如何用 Kodein 注入它?并使用我之前在其他活动或片段中注入的视图模型。

我已经尝试过中等教程这里是教程

https://proandroiddev.com/android-viewmodel-dependency-injection-with-kodein-249f80f083c9

我正在尝试从活动的视图模型访问注入结果,但是当我尝试从对话框片段访问 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
4

1 回答 1

0

您必须使用 shared 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
        })
    }
}

详情请点击这里

于 2019-08-29T12:45:16.490 回答