问题描述
我有一个ParentFragment
和ChildFragment
.他们工作得很好.
I have a ParentFragment
and a ChildFragment
. They are working pretty fine.
我的问题是,将来我可能会创建许多子片段,这使我为每个子片段编写了样板代码.因此,我想优化我的ParentFragment
,这样我就不必为以后创建的每个新子框架编写样板代码.
My problem is that in the future I might create many child fragments and this makes me write this boilerplate code for every single child fragment. Thus, I would like to optimize my ParentFragment
so that I do not have to write boilerplate code for every single new child framment I create in the future.
ParentFragment
abstract class ParentFragment<T: ViewDataBinding>: Fragment() {
@LayoutRes
abstract fun getLayoutResId(): Int
protected lateinit var binding: T
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
return DataBindingUtil.inflate<T>(inflater, getLayoutResId(), container, false).apply { binding = this }.root
}
ChildFragment
class ChildFragment: ParentFragment<FragmentChildBinding>() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//THIS IS THE BOILERPLATE METHOD I AM TALKING ABOUT.
//I WOULD LIKE TO MOVE THIS CODE IN THE PARENTFRAGMENT
initBinding()
}
@LayoutRes
override fun getLayoutResId() = R.layout.fragment_child
fun initBinding() {
val viewModel: ChildViewModel = getViewModel() //This method is from Koin
binding.viewModel = viewModel
binding.lifecycleOwner = this
}
我试图将此initBinding
方法代码移到ParentFragment
中,但出现错误.任何建议将不胜感激.
I tried to move this initBinding
method code into ParentFragment
but I got errors. Any suggestions would be greatly appreciated.
推荐答案
您需要调用binding对象上的"nofollow noreferrer"> serVariable()
,以在父片段中设置ViewModel
. (可选)如果子片段具有自己的ViewModel,则可以在父片段中通过抽象函数获取ViewModel.
You need to call serVariable()
on your binding
object to set ViewModel
in the parent Fragment. Optionally in your parent Fragment you can get ViewModel through abstract function if child Fragments have their own ViewModels.
您可以按照这篇文章来解决您的问题.
You can follow this post to solve your problem.
这篇关于优化ViewModel和DataBinding的父片段,以避免样板代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!