介绍
ViewBinding是什么?ViewBinding是一项功能,可以让你轻松地编写与视图的交互代码,它可以自动为每个xml布局文件生成一个绑定类,包含了所有ID的视图的直接引用。非常方便。
开启ViewBinding
启用它非常简单,只需要在app模块级的build.gradle中加入以下代码。
对于Android Gradle插件版本3.6.0到4.0.x:
//在app:级的build.gradle里的Android{}闭包中加入以下代码,然后右上角Sync now
//启用viewBinding
android {
...
//启用viewBinding
viewBinding {
enabled = true
}
}
对于Android Gradle插件版本4.1.0及以上:
//在app:级的build.gradle里的Android{}闭包中加入以下代码,然后右上角Sync now
//启用viewBinding
android {
...
//启用viewBinding
buildFeatures {
viewBinding = true
}
}
兄弟DataBinding
它有一个非常相近的兄弟,叫做DataBinding。这两者最显著的区别就是,DataBinding不会自动生成绑定文件,而是要手动加。DataBinding支持数据绑定与页面控件的双向绑定,能够实现数据与页面的联动,而不需要写太多代码。
我曾今也用过dataBinding也写过样例《安卓开发,DataBinding简单使用和封装》,当时对它绑定实体类做单向绑定或者双向绑定的功能一知半解,后来了解之后发现,这个功能其实并不适合复杂的业务开发,通常维持页面数据需要很多实体类,
但是 xml未必能够一一对应实体类,这样复用页面也有难度,同时绑定要在xml设置控件与实体的联系@{viewmodel.userName}。一旦业务复杂会导致代码阅读不直观,不好分析等问题,所以在了解之后,我放弃了databinding的继续研究,转而用起了viewBinding。
简单使用ViewBinding
页面中
viewBinding的页面什么都不用做,是不是很方便?
Activity中
在Activity中设置绑定,请在 Activity 的 onCreate() 方法中执行以下步骤
1、调用生成的绑定类中包含的静态 inflate() 方法。此操作会创建该绑定类的实例以供 Activity 使用。
2、通过调用getRoot()方法获取对根视图的引用。
3、将根视图传递到 setContentView(),使其成为屏幕上的活动视图。
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中设置绑定,和 Activity 的操作基本类似,唯独需要改变得是,需要在onCreateView()进行inflate()方法得获取以及视图的绑定。
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;
}
封装ViewBinding
说到封装,那我们就不得不提泛型,对于这种每个view或者每个页面得使用不同的ViewBinding实体,通过泛型进行封装,能够大大减少我们初始化对象的代码。
其实代码基本逻辑是一样的不论是在act中还是ftagment中。通过泛型来实现书写更少的代码。不过ViewBinding的初始化必须由对应页面的绑定类亲自inflate(),因为我们用的是泛型,并不能准确调用某一个VieBinding对象的inflate()方法。目前我采用的是抽象方法到子类代码里,在子类中完成精准ViewBinding的初始化。
使用的时候就继承写一行就好。
页面中
同上
Activity中
package com.bbyyxx2.myqrproject.ui.base;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;
import java.lang.reflect.ParameterizedType;
public abstract class BaseActivity<VB extends ViewBinding, VM extends ViewModel> extends AppCompatActivity {
public VB binding;
public Context context;
public Activity activity;
public VM viewModel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//ParameterizedType是获取传递过来的泛型类
ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
viewModel = new ViewModelProvider(this).get( (Class<VM>) superClass.getActualTypeArguments()[1]);
binding = inflateViewBinding(getLayoutInflater());
setContentView(binding.getRoot());
context = this;
activity = this;
initView();
initListener();
}
protected abstract VB inflateViewBinding(LayoutInflater layoutInflater);
public void initView() {
}
public void initListener(){
}
@Override
protected void onDestroy() {
super.onDestroy();
//释放持有,防止泄露
binding = null;
}
}
在fragment中
package com.bbyyxx2.myqrproject.ui.base;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;
import java.lang.reflect.ParameterizedType;
public abstract class BaseFragment<VB extends ViewBinding, VM extends ViewModel> extends Fragment {
public VB binding;
public Context context;
public Activity activity;
public VM viewModel;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
viewModel = new ViewModelProvider(this).get( (Class<VM>) superClass.getActualTypeArguments()[1]);
binding = inflateViewBinding(inflater, container);
context = requireContext();
activity = requireActivity();
initView();
initListener();
return binding.getRoot();
}
/**
* 一定要复写的,不然会报错,用于viewBinding的代码和页面关联。
* 方法内只需要一行eg:return FragmentScanBinding.inflate(inflater, container, false);
* @param inflater
* @param container
* @return
*/
protected abstract VB inflateViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container);
public void initView(){
}
public void initListener() {
}
@Override
public void onDestroyView() {
super.onDestroyView();
//释放持有,防止泄露
binding = null;
}
}
使用
public class TestFragment extends BaseFragment<FragmentTestBinding, TestViewModel> {
@Override
protected FragmentTestBinding inflateViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
return FragmentTestBinding.inflate(inflater, container, false);
}
}
使用ViewBinding
假设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=".ui.setting.SettingFragment">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
需要注意的是,ViewBinding中的id映射成字段后,是根据下划线转换为驼峰。
eg: android:id="@+id/text_title",使用的时候则是binding.textTitle;
public class TestFragment extends BaseFragment<FragmentTestBinding, TestViewModel> {
void Test(){
binding.tv.setTextView("Hello world");
}
}
优化
也可以想办法让子类一行不写的,那就是反射。
从上述代码中看到,我们其实可以取到泛型的对应class,那也就是说,通过反射我们可以直接调用对应绑定类的对应方法
(ps:注意如果项目开启了混淆,直接使用反射,在release包中会报错,因为inflate方法在混淆中会被混淆,网上的keep进行尝试后无果,后续实践后贴出解决方案已解决)
//以baseFragment举例
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
viewModel = new ViewModelProvider(this).get( (Class<VM>) superClass.getActualTypeArguments()[1]);
try {
Class<VB> cls = (Class<VB>) superClass.getActualTypeArguments()[0];
Method method = cls.getMethod("inflate", LayoutInflater.class, ViewGroup.class, Boolean.TYPE);
method.setAccessible(true);
binding = (VB) method.invoke(null, inflater,container, Boolean.FALSE);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
// binding = inflateViewBinding(inflater, container);
context = requireContext();
activity = requireActivity();
initView();
initListener();
return binding.getRoot();
}
//以baseActivity举例
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//ParameterizedType是获取传递过来的泛型类
ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
viewModel = new ViewModelProvider(this).get( (Class<VM>) superClass.getActualTypeArguments()[1]);
try {
Class<VB> cls = (Class<VB>) superClass.getActualTypeArguments()[0];
Method method = cls.getMethod("inflate", LayoutInflater.class);
method.setAccessible(true);
binding = (VB) method.invoke(null, getLayoutInflater());
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
setContentView(binding.getRoot());
context = this;
activity = this;
initView();
initListener();
}
使用反射调用inflate方法实现子类不需要干任何事情,也不存在忘写而异常闪退。
优化优化
//开启混淆
//app级的build.gradle(:app)中的Android闭包{}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
//项目中对应模块中的proguard-rules.pro中加入,这样上述优化中的反射,在混淆中就不会出问题
-keep class * extends androidx.viewbinding.ViewBinding {*;}