gpt4 book ai didi

android - 如何使用 Koin 在 BaseFragment 中注入(inject) viewModel

转载 作者:太空宇宙 更新时间:2023-11-03 13:39:34 25 4
gpt4 key购买 nike

我已经创建了一个抽象的 BaseFragment 类,它将被其他具体的 Fragment 类扩展。我想使用 Koin 在我的 BaseFragment 中注入(inject) ViewModel。这是我的 BaseFragment:

abstract class BaseFragment<out VM : BaseViewModel, DB : ViewDataBinding>(private val mViewModelClass: Class<VM>) : Fragment() {

val viewModel: VM by viewModel()

open lateinit var binding: DB

fun init(inflater: LayoutInflater, container: ViewGroup) {
binding = DataBindingUtil.inflate(inflater, getLayoutRes(), container, false)
}

open fun init() {}
@LayoutRes
abstract fun getLayoutRes(): Int

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
init(inflater, container!!)
init()
super.onCreateView(inflater, container, savedInstanceState)
return binding.root
}

open fun refresh() {}
}

但是我做不到。我正在使用 2.0.1 版本的 Koin。

最佳答案

我的情况与此相同。您还可以执行以下操作:

在扩展 BaseFragment 时将 ViewModel 添加为抽象并设置值。

我的BaseFragment有:

abstract class BaseFragment<Binding : ViewDataBinding, ViewModel : BaseViewModel> : Fragment() {
protected abstract val mViewModel: ViewModel
protected lateinit var bindingObject: Binding

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
bindingObject = DataBindingUtil.inflate(inflater, getLayoutResId(), container, false)
return bindingObject.root
}

/**
* Get layout resource id which inflate in onCreateView.
*/
@LayoutRes
abstract fun getLayoutResId(): Int

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
doDataBinding()
}

/**
* Do your other stuff in init after binding layout.
*/
abstract fun init()

private fun doDataBinding() {
bindingObject.lifecycleOwner = viewLifecycleOwner // it is extra if you want to set life cycle owner in binding
// Here your viewModel and binding variable imlementation
bindingObject.setVariable(BR.viewModel, mViewModel) // In all layout the variable name should be "viewModel"
bindingObject.executePendingBindings()
init()
}

}

这是我实际的 Fragment 实现:

class FragmentComments : BaseFragment<FragmentCommentsBinding, FragmentCommentsVM>() {
// Here is the your viewmodel imlementation
override val mViewModel: FragmentCommentsVM by viewModel()

override fun getLayoutResId(): Int = [fragment layout id like "R.layout.fragment_com"]

override fun init() {
...
}

希望对您有所帮助。如果需要更多帮助,请告诉我!

关于android - 如何使用 Koin 在 BaseFragment 中注入(inject) viewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56607721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com