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的子类 文章来源:https://www.toymoban.com/news/detail-741272.html
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的子类文章来源地址https://www.toymoban.com/news/detail-741272.html
class TestFragment : BaseFragment<FragmentTestBinding>(FragmentTestBinding::inflate) {
override fun initView(root: View, savedInstanceState: Bundle?) {
}
}
到了这里,关于(笔记)Kotlin——Android封装ViewBinding之二 优化的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!