Search code examples
androidandroid-jetpackandroid-viewbinding

ViewBinding.getRoot().getLayoutParams() always return null


When I use ViewBinding in my RecyclerView.Adapter like that:

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    val layoutInflater = LayoutInflater.from(parent.context)
    val itemView1 = MyItemBinding.inflate(layoutInflater).root
    val itemView2 = layoutInflater.inflate(R.layout.my_item, parent, false)
    val itemView3 = MyItemBinding.bind(itemView2).root
    return ViewHolder(itemView1)
}

The itemView1's layoutParams is always null -- ignore attrs in xml, and itemView2&itemView3's layoutParams works normally. So does this is a bug for ViewBinding::inflate?


Solution

  • Layout params come from the parent layout, and if you inflate without a parent, there won't be layout params. Use the overload that takes a parent layout:

    val itemView1 = MyItemBinding.inflate(layoutInflater, parent, false).root
    

    (Would be a good idea to also capture the binding reference and not throw it away immediately, too.)