ViewBinding的优点:
仅仅支持绑定 View
不需要在布局文件中添加layout标签
需要在模块级build.gradle文件中添加 viewBinding = true 即可使用
效率高于DataBinding,因为避免了与数据绑定相关的开销和性能问题
相比于kotlin-android-extensions插件避免了空异常
Gradle配置:
// Android Studio 3.6 android { viewBinding { enabled = true } } // Android Studio 4.0 android { buildFeatures { viewBinding = true } }
ViewBinding简单使用:
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import com.example.mychartdemo.databinding.ActivityMain2Binding class MainActivity2 : AppCompatActivity() { private lateinit var binding: ActivityMain2Binding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMain2Binding.inflate(layoutInflater) setContentView(binding.root) binding.btn.setOnClickListener { Toast.makeText(this,"点击了按钮",Toast.LENGTH_SHORT).show() } } }
参考于:
https://blog.csdn.net/tanlove1314/article/details/114240299
https://www.jianshu.com/p/66728b95baaa
https://www.cnblogs.com/ymtianyu/p/13208548.html