Android App封装 —— ViewBinding

5,100 阅读5分钟

项目搭建经历记录

  1. Android App封装 ——架构(MVI + kotlin + Flow)
  2. Android App封装 —— ViewBinding
  3. Android App封装 —— DI框架 Hilt?Koin?
  4. Android App封装 —— 实现自己的EventBus

一、背景

在前面的Github wanandroid项目中可以看到,我获取控件对象还是用的findviewbyId

button = findViewById(R.id.button)
viewPager = findViewById(R.id.view_pager)
recyclerView = findViewById(R.id.recycler_view)

现在肯定是需要对这个最常用的获取View的findViewById代码进行优化,主要是有两个原因

  1. 过于冗余

    findViewById对应所有的View都要书写findViewById(R.id.xxx)的方法,代码过于繁琐

  2. 不安全

    强制转换不安全,findViewById获取到的是一个View对象,是需要强转的,一旦类型给的不对则会出现异常,比如将TextView错转成ImageView

所以我们需要一个框架解决这个问题,大致是有三个方案

二、方案

方案一 butterkniife

这个应该很多人都用过,由大大佬JakeWharton开发,通过注解生成findViewById的代码来获取对应的View。

@BindView(R.id.button) 
EditText mButton;

但是2020年3月份,大佬已在GitHub上说明不再维护,推荐使用 ViewBinding了。

方案二 kotlin-android-extensions(KAE)

kotlin-android-extensions只需要直接引入布局可以直接使用资源Id访问View,节省findviewbyid()。

import kotlinx.android.synthetic.main.<布局>.*

button.setOnClickListener{...} 

但是这个插件也已经被Google废弃了,会影响效率并且安全性和兼容性都不太友好,Google推荐ViewBinding替代

方案三 ViewBinding

既然都推荐ViewBinding,那现在来看看ViewBinding是啥。官网是这么说的

通过ViewBinding功能,您可以更轻松地编写可与视图交互的代码。在模块中启用视图绑定之后,系统会为该模块中的每个 XML 布局文件生成一个绑定类。绑定类的实例包含对在相应布局中具有 ID 的所有视图的直接引用。在大多数情况下,视图绑定会替代 findViewById。

简而言之就是就是替代findViewById来获取View的。那我们来看看ViewBinding如何使用呢?

三、ViewBinding使用

1. 条件

确保你的Android Studio是3.6或更高的版本

ViewBinding在 Android Studio 3.6 Canary 11 及更高版本中可用

2. 启用ViewBinding

在模块build.gradle文件android节点下添加如下代码

android {
    viewBinding{
        enabled = true
    }
}

Android Studio 4.0 中,viewBinding 变成属性被整合到了 buildFeatures 选项中,所以配置要改成:

// Android Studio 4.0
android {
     buildFeatures {
          viewBinding = true
     }
}

配置好后就已经启用好了ViewBinding,重新编译后系统会为每个布局生成对应的Binding类,类中包含布局ID对应的View引用,并采取驼峰式命名。

3. 使用

以activity举例,我们的MainActivity的布局是activity_main,之前我们布局代码是:

class MainActivity : BaseActivity() {

    private lateinit var button: Button
    private lateinit var viewPager: ViewPager2
    private lateinit var recyclerView: RecyclerView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button = findViewById(R.id.button)
        button.setOnClickListener { ... }
    }
}

现在就要改为

  1. 对应的Binding类如ActivityMainBinding类去用inflate加载布局
  2. 然后通过getRoot获取到View
  3. 将View传入到setContentView(view:View)中

Activity就能显示activity_main.xml这个布局的内容了,并可以通过Binding对象直接访问对应View对象。

class MainActivity : BaseActivity() {

    private lateinit var mBinding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        mBinding.button.setOnClickListener { ... }
    }
}

而在其他UI elements中,如fragment、dialog、adapter中,使用方式大同小异,都是通过inflate去加载出View,然后后面加以使用。

四、原理

生成的类可以在/build/generated/data_binding_base_class_source_out下找到

public final class ActivityMainBinding implements ViewBinding {
  @NonNull
  private final ConstraintLayout rootView;

  @NonNull
  public final Button button;

  @NonNull
  public final RecyclerView recyclerView;

  @NonNull
  public final ViewPager2 viewPager;

  private ActivityMainBinding(@NonNull ConstraintLayout rootView, @NonNull Button button,
      @NonNull RecyclerView recyclerView, @NonNull ViewPager2 viewPager) {
    this.rootView = rootView;
    this.button = button;
    this.recyclerView = recyclerView;
    this.viewPager = viewPager;
  }

  @Override
  @NonNull
  public ConstraintLayout getRoot() {
    return rootView;
  }

  @NonNull
  public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater) {
    return inflate(inflater, null, false);
  }

  @NonNull
  public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater,
      @Nullable ViewGroup parent, boolean attachToParent) {
    View root = inflater.inflate(R.layout.activity_main, parent, false);
    if (attachToParent) {
      parent.addView(root);
    }
    return bind(root);
  }

  @NonNull
  public static ActivityMainBinding bind(@NonNull View rootView) {
    // The body of this method is generated in a way you would not otherwise write.
    // This is done to optimize the compiled bytecode for size and performance.
    int id;
    missingId: {
      id = R.id.button;
      Button button = ViewBindings.findChildViewById(rootView, id);
      if (button == null) {
        break missingId;
      }

      id = R.id.recycler_view;
      RecyclerView recyclerView = ViewBindings.findChildViewById(rootView, id);
      if (recyclerView == null) {
        break missingId;
      }

      id = R.id.view_pager;
      ViewPager2 viewPager = ViewBindings.findChildViewById(rootView, id);
      if (viewPager == null) {
        break missingId;
      }

      return new ActivityMainBinding((ConstraintLayout) rootView, button, recyclerView, viewPager);
    }
    String missingId = rootView.getResources().getResourceName(id);
    throw new NullPointerException("Missing required view with ID: ".concat(missingId));
  }
}

可以看到关键的方法就是这个bind方法,里面通过ViewBindings.findChildViewById获取View对象,而继续查看这个方法

public class ViewBindings {

    private ViewBindings() {
    }

    /**
     * Like `findViewById` but skips the view itself.
     *
     * @hide
     */
    @Nullable
    public static <T extends View> T findChildViewById(View rootView, @IdRes int id) {
        if (!(rootView instanceof ViewGroup)) {
            return null;
        }
        final ViewGroup rootViewGroup = (ViewGroup) rootView;
        final int childCount = rootViewGroup.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final T view = rootViewGroup.getChildAt(i).findViewById(id);
            if (view != null) {
                return view;
            }
        }
        return null;
    }
}

可见还是使用的findViewById,ViewBinding这个框架只是帮我们在编译阶段自动生成了这些findViewById代码,省去我们去写了。

五、优缺点

优点

  1. 对比kotlin-extension,可以控制访问作用域,kotlin-extension可以访问不是该布局下的view;
  2. 对比butterknife,减少注解以及id的一对一匹配
  3. 兼容Kotlin、Java;
  4. 官方推荐。

缺点

  1. 增加编译时间,因为ViwBinding是在编译时生成的,会产生而外的类,增加包的体积;
  2. include的布局文件无法直接引用,需要给include给id值,然后间接引用;

整体来说ViewBinding的优点还是远远大于缺点的,所以可以放心使用。

六、 封装

既然选择了方案ViewBinding,那我们要在项目中使用,肯定还需要对他加一些封装,我们可以用泛型封装setContentView的代码

abstract class BaseBindingActivity<VB : ViewBinding>(
    val block: (LayoutInflater) -> VB
) : BaseActivity() {
    private var _binding: VB? = null
    protected val binding: VB
        get() = requireNotNull(_binding) { "The property of binding has been destroyed." }

    override fun onCreate(savedInstanceState: Bundle?) {
        _binding = block(layoutInflater)
        setContentView(binding.root)
        super.onCreate(savedInstanceState)
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}
class MainActivity : BaseBindingActivity<ActivityMainBinding>({
    ActivityMainBinding.inflate(it)
})

    override fun initView(savedInstanceState: Bundle?) {
        binding.button.setOnClickListener {
            ...
        }
    }

}

这样在Activity中使用起来就很方便,fragment也可以做类似的封装

abstract class BaseBindingFragment<VB : ViewBinding>(
    val block: (LayoutInflater) -> VB
) : BaseFragment() {
    private var _binding: VB? = null
    protected val binding: VB
        get() = requireNotNull(_binding) { "The property of binding has been destroyed." }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = block(layoutInflater)
        return binding.root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

注意

这里会发现Fragment和Activity的封装方式不一样,没有用lateinit
因为binding变量只有在onCreateView与onDestroyView才是可用的,而fragment的生命周期和activity的不同,fragment可以超出其视图的生命周期,比如fragment hide的时候,如果不将这里置为空,有可能引起内存泄漏
所以我们要在onCreateView中创建,onDestroyView置空。

七、总结

ViewBinding相比优点还是很多的,解决了安全性问题和兼容性问题,所以我们可以放心大胆的使用。

项目源码地址: Github wanandroid

相关链接: Android App封装 ——架构(MVI + kotlin + Flow)