以下是我的代码片段。
class DashBoardHolder(val binding: ActivityDashBoardBinding) : RecyclerView.ViewHolder(binding.root) {
internal var tvName: TextView = itemView.findViewById(R.id.textViewGrandrukName)
以下是我的代码片段。
class DashBoardHolder(val binding: ActivityDashBoardBinding) : RecyclerView.ViewHolder(binding.root) {
internal var tvName: TextView = itemView.findViewById(R.id.textViewGrandrukName)
binding.root is reference to root view.
root view is outermost view container in your layout.
when you call binding.root ,will return LinearLayout root view.(below xml code)
before view binding when we call findViewById(), we can call any id from any layout even other than given layout .it won't show compile time error like hey you have called id from other layout ,that view is not in your provided layout .when we run we will get "Null" object reference .but view binding will give all binding id from root view.we can only call biding.name and biding.button.we can not call other layout binding id.so when we use view biding,we won't get "NULL". this is specific feature of view binding .All because of root view.
<LinearLayout ... >
<TextView android:id="@+id/name" />
<ImageView android:cropToPadding="true" />
<Button android:id="@+id/button"
android:background="@drawable/rounded_button" />
</LinearLayout>
访问这个链接:https://developer.android.com/topic/libraries/view-binding#usage
文档如下解释:每个绑定类还包括一个getRoot()方法,用于提供对相应布局文件的根视图的直接引用。在此示例中,ResultProfileBinding类中的getRoot()方法返回LinearLayout根视图。