Search code examples
androidkotlinandroid-recyclerviewadapterandroid-viewholder

What does binding.root indicates for?


Following is my code snippet.

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

Solution

    • 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>