注意:您需要至少使用 Android Studio 3.6 Canary 11 才能使用 View Binding

    要将 ViewBinding 添加到我们的应用程序中,我们需要将以下内容添加到 build.gradle 文件中:

    1. android {
    2. viewBinding {
    3. enabled = true
    4. }
    5. }

    注:Android Studio 4.0 以上 ViewBinding 启用方式变更如下

    1. android {
    2. ...
    3. buildFeatures {
    4. viewBinding true
    5. }
    6. }

    接下来新建一个布局文件activity_view_binding,内容如下

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. xmlns:app="http://schemas.android.com/apk/res-auto"
    4. xmlns:tools="http://schemas.android.com/tools"
    5. android:layout_width="match_parent"
    6. android:layout_height="match_parent">
    7. <TextView
    8. android:id="@+id/text"
    9. android:layout_width="wrap_content"
    10. android:layout_height="wrap_content"
    11. android:layout_margin="10dp"
    12. app:layout_constraintStart_toStartOf="parent"
    13. app:layout_constraintTop_toTopOf="parent"
    14. tools:text="111" />
    15. <android.support.v7.widget.AppCompatImageView
    16. android:id="@+id/image"
    17. android:layout_width="0dp"
    18. android:layout_height="0dp"
    19. android:layout_margin="10dp"
    20. app:layout_constraintDimensionRatio="1:1"
    21. app:layout_constraintStart_toStartOf="parent"
    22. app:layout_constraintTop_toBottomOf="@id/text"
    23. app:layout_constraintWidth_percent="0.4" />
    24. </android.support.constraint.ConstraintLayout>

    然后在Activity等需要使用布局的类中进行ViewBinding的初始化及使用,如下

    1. public class ViewBindingActivity extends AppCompatActivity {
    2. private ActivityViewBindingBinding viewBinding;
    3. @Override
    4. protected void onCreate(@Nullable Bundle savedInstanceState) {
    5. super.onCreate(savedInstanceState);
    6. viewBinding = ActivityViewBindingBinding.inflate(LayoutInflater.from(this));
    7. setContentView(viewBinding.getRoot());
    8. viewBinding.text.setText("view binding");
    9. viewBinding.image.setImageResource(R.color.black);
    10. }
    11. }

    ViewBinding 不用再手动进行类型转换,也避免了空指针错误。如果不想生成 ViewBinding,可以在布局的根视图上使用tools:viewBindingIgnore="true"

    原文链接:https://blog.csdn.net/jklwan/java/article/details/102767871