binding.root 代表什么?

问题描述 投票:0回答:2

以下是我的代码片段。

class DashBoardHolder(val binding: ActivityDashBoardBinding) : RecyclerView.ViewHolder(binding.root) {
    internal var tvName: TextView = itemView.findViewById(R.id.textViewGrandrukName)
android kotlin android-recyclerview adapter android-viewholder
2个回答
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>
    

0
投票
  • 访问此:https://developer.android.com/topic/libraries/view-binding#usage

  • 文档是这样解释的:

    Every binding class also includes a getRoot() method, providing a direct reference for the root view of the corresponding layout file. In this example, the getRoot() method in the ResultProfileBinding class returns the LinearLayout root view.

© www.soinside.com 2019 - 2024. All rights reserved.