Binding.root 表示什么?

Hub*_*ari 4 android adapter kotlin android-viewholder android-recyclerview

以下是我的代码片段。

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

and*_*ner 8

  • 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>
    
    Run Code Online (Sandbox Code Playgroud)