android 中具有视图绑定的 BaseFragment

BaseFragment with viewbinding in android

BaseFragment.kt:

abstract class BaseFragment<VM : ViewModel, VB : ViewBinding> : Fragment() {

    protected abstract val mViewModel: VM
    protected lateinit var mViewBinding: VB

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mViewBinding = getViewBinding(inflater, container)
        return mViewBinding.root
    }

    abstract fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?): VB
}

DemoFragment.kt:

class DemoFragment : BaseFragment<DemoBaseViewModel, FragmentDemoBinding>() {

    override val mViewModel: DemoBaseViewModel by viewModels()

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

    override fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentDemoBinding {
        return FragmentDemoBinding.inflate(inflater, container, false)
    }
}

使用这样的设计,您的派生 class onCreateView() 应该调用初始化绑定的基础 class super.onCreateView()

或者正如 Primož Ivančič 指出的那样,您根本不需要覆盖 onCreateView()