【发布时间】:2019-06-15 05:48:04
【问题描述】:
我创建了一个抽象的BaseFragment 类,它将被其他具体的Fragment 类扩展。我想使用Koin 在我的BaseFragment 中注入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。
【问题讨论】:
-
你得到什么错误?顺便说一句,如果
container是null,您的代码可能会崩溃,我建议您在此处使用安全运算符以防万一。 -
我收到
Cannot use VM as reified type parameter. Use a class Instead@JavierMendonça -
是的,我在想这些方面的东西。我不确定 Koin 能否弄清楚
VM是什么类型。在这种情况下,VM应该被具体化,以便 Kotlin 可以推断类型,以便 Koin 可以工作,但你不能在类定义中使用reified但是职能。mViewModelClass是什么?不好用它做什么? -
恐怕在不知道
VM是什么类型的情况下,您将无法以这种方式一般地注入它。把那个代码取出到每个片段,就一行代码??????????♂️。不过,您可以这样做的数据绑定,只需注意container!! -
尽管我不确定以这种方式完成数据绑定是否值得,但您需要在使用它的每个片段中强制转换它。您可以在每个片段中执行此操作,为了使其更具表现力,您可以使用此扩展功能:
inline fun <reified VD : ViewDataBinding> ViewGroup.bind(layoutId: Int, attachToRoot: Boolean = false): VD = DataBindingUtil.inflate(LayoutInflater.from(context), layoutId, this, attachToRoot)。那你就做view.bind<YourBindingClass>(R.layout.your_binding),很方便。
标签: android kotlin android-viewmodel koin