Android ViewBinding使用

1,576 阅读5分钟

一、接入视图绑定 通过视图绑定功能,您可以更轻松地编写可与视图交互的代码。在模块中启用视图绑定之后,系统会为该模块中的每个 XML 布局文件生成一个绑定类。绑定类的实例包含对在相应布局中具有 ID 的所有视图的直接引用。 在大多数情况下,视图绑定会替代findViewById。 1.1设置说明 视图绑定功能可按模块启用。要在某个模块中启用视图绑定,请将viewBinding元素添加到其build.gradle文件中,如下例所示:

buildTypes {
        ...
        android.buildFeatures {
            viewBinding = true
        }
    }

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

<LinearLayout
            ...
            tools:viewBindingIgnore="true" >
        ...
    </LinearLayout>

1.2用法 为某个模块启用视图绑定功能后,系统会为该模块中包含的每个 XML 布局文件生成一个绑定类。每个绑定类均包含对根视图以及具有 ID 的所有视图的引用。系统会通过以下方式生成绑定类的名称:将 XML 文件的名称转换为驼峰式大小写,并在末尾添加“Binding”一词。 例如,假设某个布局文件的名称为result_profile.xml:

<LinearLayout ... >
        <TextView android:id="@+id/name" />
        <ImageView android:cropToPadding="true" />
        <Button android:id="@+id/button"
            android:background="@drawable/rounded_button" />
    </LinearLayout>

所生成的绑定类的名称就为ResultProfileBinding。此类具有两个字段:一个是名为name的TextView,另一个是名为button的Button。该布局中的ImageView没有 ID,因此绑定类中不存在对它的引用。 每个绑定类还包含一个getRoot()方法,用于为相应布局文件的根视图提供直接引用。在此示例中,ResultProfileBinding类中的getRoot()方法会返回LinearLayout根视图。 以下几个部分介绍了生成的绑定类在 Activity 、Fragment 、dialog中的使用。 1.2.1在 Activity 中使用视图绑定 如需设置绑定类的实例以供 Activity 使用,请在 Activity 的onCreate()方法中执行以下步骤:

  1. 调用生成的绑定类中包含的静态inflate()方法。此操作会创建该绑定类的实例以供 Activity 使用。
  2. 通过调用getRoot()方法或使用Kotlin 属性语法获取对根视图的引用。
  3. 将根视图传递到setContentView(),使其成为屏幕上的活动视图。
    binding.name.text = viewModel.name
    binding.button.setOnClickListener { viewModel.userClicked() }

1.2.2在 Fragment 中使用视图绑定 如需设置绑定类的实例以供 Fragment 使用,请在 Fragment 的onCreateView()方法中执行以下步骤:

  1. 调用生成的绑定类中包含的静态inflate()方法。此操作会创建该绑定类的实例以供 Fragment 使用。
  2. 通过调用getRoot()方法或使用Kotlin 属性语法获取对根视图的引用。
  3. 从onCreateView()方法返回根视图,使其成为屏幕上的活动视图。
private var _binding: ResultProfileBinding? = null
    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = ResultProfileBinding.inflate(inflater, container, false)
        val view = binding.root
        return view
    }

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

现在即可使用该绑定类的实例来引用任何视图:

    binding.name.text = viewModel.name
    binding.button.setOnClickListener { viewModel.userClicked() }

1.2.3在 Dialog 中使用视图绑定 如需设置绑定类的实例以供 Fragment 使用,请在 Fragment 的onCreateView()方法中执行以下步骤:

  1. 调用生成的绑定类中包含的静态inflate()方法。此操作会创建该绑定类的实例以供 Dialog 使用。
  2. 通过调用getRoot()方法或使用Kotlin 属性语法获取对根视图的引用。
  3. 从onCreate()方法返回根视图,使其成为屏幕上的活动视图。
override fun onCreate(savedInstanceState: Bundle?) {
    binding = DialogAppBinding.inflate(layoutInflater)
    setContentView(binding.root)
}

1.2.4在 Adapter 中使用视图绑定 如需设置绑定类的实例以供 Fragment 使用,请在 Fragment 的onCreateView()方法中执行以下步骤:

  1. 调用生成的绑定类中包含的静态inflate()方法。此操作会创建该绑定类的实例以供 Adapter 使用。
  2. 通过调用getRoot()方法或使用Kotlin 属性语法获取对根视图的引用。
  3. 从onCreateViewHolder(parent: ViewGroup, viewType: Int)方法返回根视图,使其成为屏幕上的活动视图。
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return AudioListViewHolder(
        GaItemAudioLayoutBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
            )
    )
}

1.2.5在 View 中使用视图绑定 这里以EmptyView为例

View.inflate(context, R.layout.ui_empty_view_layout, this)
//代替上方
val binding = UiEmptyViewLayoutBinding.inflate(LayoutInflater.from(mContext), this, true)

1.2.6在 include 标签中使用视图绑定 include标签不带merge标签,需要给include标签添加 id, 直接使用 id 即可,用法如下所示。

<include
    android:id="@+id/include"
    layout="@layout/layout_include_item" />
    
val binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)
binding.include.includeTvTitle.setText("使用 include 布局中的控件, 不包含 merge")

include标签带merge标签,注意这里和 DataBinding 用法不一样,给include标签添加 id,ViewBinding 的用法如下所示。

<include layout="@layout/layout_merge_item" />

val binding: ActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)
val mergeItemBinding = LayoutMergeItemBinding.bind(binding.root)
mergeItemBinding.mergeTvTitle.setText("使用 include 布局中的控件, 包含 merge")

1.2.7在 ViewStub 标签中使用视图绑定 根据实践证明,截止到这篇文章发布时,在Android Studio 4.2.0 bata 2中,无法直接在 ViewBinding 布局中使用ViewStub标签,仅仅只能在 DataBinding 布局(带layout标签)中使用,详见 issue stackoverflow.com/questions/5… 因为没有找到比较权威的资料证明,这里建议小伙们直接在项目Binding中进行尝试,如果有其他在 ViewBinding 布局中的实现方式,欢迎留言告知我

二、简易封装 2.1类似之前的EmptyView:BasePage 因为EmptyView是非必须的,所以这里并没有采用抽象方法定义

/**
 * 添加通用的空view
 */
public GAEmptyView getPageEmptyView() {
return null;
}

public void setPageLoading() {
if (getPageEmptyView() != null) {
        getPageEmptyView().setLoading();
}
}

public void setPageLoadSuccess() {
if (getPageEmptyView() != null) {
        getPageEmptyView().setLoadSuccess();
}
}

public void setPageLoadFailed() {
if (getPageEmptyView() != null) {
        getPageEmptyView().setLoadFailed();
}
}

public void setPageEmpty() {
if (getPageEmptyView() != null) {
        getPageEmptyView().setEmpty();
}
}

//暂时未知
public void setPageRecipeEmpty() {

}

public void setPageEmptyViewStatus(EmptyStatus status) {
if (getPageEmptyView() != null) {
switch (status) {
case LOADING:
                setPageLoading();
                break;
            case LOAD_SUCCESS:
                setPageLoadSuccess();
                break;
            case LOAD_FAILED:
                setPageLoadFailed();
                break;
            case EMPTY:
                setPageEmpty();
                break;
            case RECIPE_EMPTY:
                setPageRecipeEmpty();
                break;
            default:
// TODO: 2020/12/15 未知
break;
}
    }

}

2.2ViewBinding简单封装 2.2.1依托于基类GABaseBindingActivity

abstract class GABaseBindingActivity<VB : ViewBinding> : GABaseActivity() {

    protected var _binding: VB? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = getBinding()
        _binding?.let {
            setContentView(it.root)
        }?:let {
            Log.d("Warning","getBinding()为空,如需使用ViewBinding请进行相关配置")
        }
    }

    abstract fun getBinding(): VB
}

2.2.2不依托于基类的封装 封装原因需要稍微懂点原理以及有kotlin语法基础

inline fun <reified VB : ViewBinding> inflateBinding(layoutInflater: LayoutInflater) =
VB::class.java.getMethod("inflate", LayoutInflater::class.java)
        .invoke(null, layoutInflater) as VB

inline fun <reified VB : ViewBinding> Activity.inflate() = lazy {
inflateBinding<VB>(layoutInflater).apply { setContentView(root) }
}

inline fun <reified VB : ViewBinding> Dialog.inflate() = lazy {
inflateBinding<VB>(layoutInflater).apply { setContentView(root) }
}