-
- android {
- .......
-
- viewBinding {
- enabled = true
- }
-
- }
添加两个扩展函数,分别对应Activity和Fragment
- inline fun
AppCompatActivity.viewBinding(crossinline bindingInflater: (LayoutInflater) -> T) = - lazy(LazyThreadSafetyMode.NONE) {
- bindingInflater.invoke(layoutInflater)
- }
-
-
- inline fun
Fragment.viewBinding(crossinline bindingInflater: (LayoutInflater, ViewGroup? , Boolean) -> T) = - lazy(LazyThreadSafetyMode.NONE) {
- bindingInflater.invoke(layoutInflater, view?.parent as? ViewGroup, false)
- }
BaseActivity
- public abstract class BaseActivity<VB : ViewBinding>(inflater: (LayoutInflater) -> VB) :
- AppCompatActivity() {
-
- protected val binding by viewBinding(inflater)
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(binding.root)
- initView()
- initData()
- }
-
- protected fun initView() {}
-
- protected fun initData() {}
-
- }
继承自BaseActivity的子类
- class VideoPlayerActivity : BaseActivity<ActivityVideoPlayerBinding>(ActivityVideoPlayerBinding::inflate),
- View.OnClickListener {
-
- override fun initView() {
- binding.play.setOnClickListener(this)
- }
-
- override fun onClick(p0: View?) {
-
- }
-
- }
- abstract class BaseFragment<VB : ViewBinding>(inflater: (LayoutInflater, ViewGroup?, Boolean) -> VB)
- : Fragment() {
-
- protected val binding by viewBinding(inflater)
-
- override fun onCreateView(
- inflater: LayoutInflater,
- container: ViewGroup?,
- savedInstanceState: Bundle?
- ): View? {
- initView(binding.root, savedInstanceState)
- return binding.root
- }
-
- abstract fun initView(root: View, savedInstanceState: Bundle?)
-
- }
继承自BaseFragment的子类
- class TestFragment : BaseFragment<FragmentTestBinding>(FragmentTestBinding::inflate) {
-
- override fun initView(root: View, savedInstanceState: Bundle?) {
- }
-
- }