首页 > 解决方案 > binding.root 表示什么?

问题描述

以下是我的代码片段。

class DashBoardHolder(val binding: ActivityDashBoardBinding) : RecyclerView.ViewHolder(binding.root) {
    internal var tvName: TextView = itemView.findViewById(R.id.textViewGrandrukName)

标签: androidkotlinandroid-recyclerviewadapterandroid-viewholder

解决方案


  • binding.root 是对根视图的引用。

  • 根视图是 布局中最外层的视图容器。

  • 当您调用 binding.root 时,将返回 LinearLayout 根视图。(以下 xml 代码)

  • 在视图绑定之前,当我们调用 findViewById() 时,我们可以从任何布局调用任何 id,即使给定布局除外。它不会显示编译时错误,就像你从其他布局调用 id 一样,该视图不在您提供的布局中.当我们运行时,我们将获得“Null”对象引用。但是视图绑定将从根视图提供所有绑定ID。我们只能调用biding.name和biding.button。我们不能调用其他布局绑定id。所以当我们使用时查看投标,我们不会得到“NULL”。这是视图绑定的特定功能。都是因为根视图。

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

推荐阅读