我创建了一个抽象的 BaseFragment 类,它将被其他具体的 Fragment 类扩展。我想使用 ViewModel 在我的 BaseFragment 中注入(inject) Koin 。这是我的 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() {}
}

但我不能这样做。我正在使用 Koin 的 2.0.1 版本。

最佳答案

在我的情况下,我有同样的情况。你也可以像下面这样:

当您扩展 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/

10-10 02:16