sag*_*uri 7 android kotlin android-viewmodel koin
我创建了一个抽象BaseFragment类,它将被其他具体Fragment类扩展。我想注入ViewModel我BaseFragment使用的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() {}
}
Run Code Online (Sandbox Code Playgroud)
但我不能这样做。我正在使用2.0.1Koin 版本。
pRa*_*NaY 11
在我的情况下,我有同样的情况。你也可以像下面这样:
当您扩展 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()
}
}
Run Code Online (Sandbox Code Playgroud)
这是我实际的 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() {
...
}
Run Code Online (Sandbox Code Playgroud)
我希望这可以帮助你。如果需要更多帮助,请告诉我!
| 归档时间: |
|
| 查看次数: |
3570 次 |
| 最近记录: |