0. 在app模块的build.gradle文件中添加如下配置开启ViewBinding
android {
.......
viewBinding {
enabled = true
}
}
1. 新建一个Ext.kt文件
添加两个扩展函数,分别对应Activity和Fragment
inline fun <T : ViewBinding> AppCompatActivity.viewBinding(crossinline bindingInflater: (LayoutInflater) -> T) =
lazy(LazyThreadSafetyMode.NONE) {
bindingInflater.invoke(layoutInflater)
}
inline fun <T : ViewBinding> Fragment.viewBinding(crossinline bindingInflater: (LayoutInflater, ViewGroup? , Boolean) -> T) =
lazy(LazyThreadSafetyMode.NONE) {
bindingInflater.invoke(layoutInflater, view?.parent as? ViewGroup, false)
}
2. Activity中使用
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?) {
}
}
3. Fragment中使用
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?) {
}
}