Android View Binding的使用

什么是View Binding

官方文档

View Binding是Android Studio 3.6推出的新特性,目的是为了替代findViewById(内部实现还是使用findViewById)。。在启动视图绑定后,系统会为改模块中的每个xml文件生成一个绑定类,绑定类的实例包含对在相应布局中具有 ID 的所有视图的直接引用。

View Binding 的优点

  • Null 安全:由于视图绑定会创建对视图的直接引用,因此不存在因视图 ID 无效而引发 Null 指针异常的风险。此外,如果视图仅出现在布局的某些配置中,则绑定类中包含其引用的字段会使用 @Nullable 标记。
  • 类型安全:每个绑定类中的字段均具有与它们在 XML 文件中引用的视图相匹配的类型。这意味着不存在发生类转换异常的风险。

如何启用View Binding 功能

android {
        ...
        viewBinding {
            enabled = true
        }
    }
} 

如果想在生成绑定类时忽略某个布局文件,将 tools:viewBindingIgnore="true" 属性添加到相应布局文件的根视图中:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:viewBindingIgnore="true"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

怎么去使用View Binding

为用视图绑定功能后,系统会为该模块中包含的每个 XML 布局文件生成一个绑定类。这个类的类名是以xml布局文件名去掉下换线后,单词首字母大写加上Binding命名的。如activity_main.xml生成的类ActivityMainBinding.

  • 如何在Activity中设置绑定,请在 Activity 的 onCreate() 方法中执行以下步骤:

    1. 调用生成的绑定类中包含的静态 inflate() 方法。此操作会创建该绑定类的实例以供 Activity 使用。

    2. 通过调用 getRoot() 方法或使用 Kotlin 属性语法获取对根视图的引用。

    3. 将根视图传递到 setContentView(),使其成为屏幕上的活动视图。

    //activity_main.xml
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <Button
            android:id="@+id/button"
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:text="这是按钮"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView" />
    
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="Hello World!"
            app:layout_constraintBottom_toTopOf="@+id/button"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>	
    
    //MainActivity.java
    public class MainActivity extends AppCompatActivity {
        private ActivityMainBinding binding;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //关键代码
            binding = ActivityMainBinding.inflate(getLayoutInflater());
            View rootView = binding.getRoot();
            setContentView(rootView);
            //如何使用
            binding.textView.setText("这是修改的");
            binding.button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.d("Main","点击了按钮");
                }
            });
    
        }
    }
    
  • 如何在 Fragment 中使用视图绑定 请在 Fragment 的 onCreateView()方法中执行以下步骤(注意:Fragment 的存在时间比其视图长。请务必在 Fragment 的 onDestroyView() 方法中清除对绑定类实例的所有引用。)

    1. 调用生成的绑定类中包含的静态 inflate() 方法。此操作会创建该绑定类的实例以供 Fragment 使用。

    2. 通过调用 getRoot() 方法或使用 Kotlin 属性语法获取对根视图的引用。

    3. onCreateView() 方法返回根视图,使其成为屏幕上的活动视图。

      如果view已经创建可以在onViewCreated()中使用bind(view)方法。官方示例

    //fragment_my.xml
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:text="这是Fragment按钮"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView" />
    
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="40dp"
            android:gravity="center"
            android:text="这是FragmentTextView"
            app:layout_constraintBottom_toTopOf="@+id/button"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
    public class MyFragment extends Fragment {
      private FragmentMyBinding binding;
    
      public MyFragment() {
    
      }
    
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
    
      }
    
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                               Bundle savedInstanceState) {
          binding = FragmentMyBinding.inflate(inflater, container, false);
          return binding.getRoot();
      }
    
      @Override
      public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
          super.onViewCreated(view, savedInstanceState);
          binding.textView.setText("这是Fragment");
          binding.button.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  Log.d("Fragment", "点击了按钮");
              }
          });
      }
    
      @Override
      public void onDestroy() {
          super.onDestroy();
          binding = null;
      }
    
    
    //在onViewCreated中使用View Binding
    public class MyFragment extends Fragment {
      private FragmentMyBinding binding;
    
      public MyFragment() {
    
      }
    
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
    
      }
    
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                               Bundle savedInstanceState) {
          return inflater.inflate(R.layout.fragment_my,container,false);
      }
    
      @Override
      public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
          super.onViewCreated(view, savedInstanceState);
          FragmentMyBinding binding = FragmentMyBinding.bind(view);
          this.binding = binding;
    
          binding.textView.setText("这是Fragment");
          binding.button.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                  Log.d("Fragment", "点击了按钮");
              }
          });
      }
    
      @Override
      public void onDestroy() {
          super.onDestroy();
          binding = null;
      }
    
    

    使用View Binding 写的基类

    public class BaseActivity<T extends ViewBinding> extends AppCompatActivity {
      protected T viewBinding;
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
          Class cls = (Class) type.getActualTypeArguments()[0];
          try {
              Method inflate = cls.getDeclaredMethod("inflate", LayoutInflater.class);
              viewBinding = (T) inflate.invoke(null, getLayoutInflater());
              setContentView(viewBinding.getRoot());
          } catch (NoSuchMethodException | IllegalAccessException| InvocationTargetException e) {
              e.printStackTrace();
          }
      }
    }
    
    //使用
    
    public class MainActivity extends BaseActivity<ActivityMainBinding> {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            viewBinding.button.setText("这是 MainActivity ViewBinding");
            viewBinding.button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.d("MainView","点击按钮");
                }
            });
        }
    }
    
    public class BaseFragment<T extends ViewBinding> extends Fragment {
        protected T viewBinding;
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
            Class cls = (Class) type.getActualTypeArguments()[0];
            try {
                Method inflate = cls.getDeclaredMethod("inflate", LayoutInflater.class, ViewGroup.class, boolean.class);
                viewBinding = (T) inflate.invoke(null, inflater, container, false);
            }  catch (NoSuchMethodException | IllegalAccessException| InvocationTargetException e) {
                e.printStackTrace();
            }
            return viewBinding.getRoot();
        }
    }
    
    //使用
    public class MainFragment extends BaseFragment<FragmentMainBinding>{
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            viewBinding.button.setText("这是 MainFragment ViewBinding");
            viewBinding.button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.d("MainView","点击按钮");
                }
            });
        }
    }
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值