What the actual meaning `Caused by: java.lang.RuntimeException: view must have a tag`?

后端 未结 9 2082
轮回少年
轮回少年 2021-02-20 06:25

Please inform me if knowing whats tag that wanted.

Caused by: java.lang.RuntimeException: view must have a tag

__BaseActivity.java

          


        
9条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-20 06:52

    Another scenario where this error occurs is in a RecyclerView's ViewHolder.

    Avoid initialising a binding instance in the ViewHolder's bind method

    class BindingAdapter(private val items: List): RecyclerView.Adapter() {
          override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingHolder {}
    
          override fun onBindViewHolder(holder: BindingHolder, position: Int) {
               holder.bindItem(items[position])
          }
     }
    
    class BindingHolder(view: View): RecyclerView.ViewHolder(view) {
        fun bindItem(item: Any) {
            //Don't do this
            val binding = ItemSampleBinding.bind(itemView)
        }
    }
    

    The databinding instance should be initialised outside the bind method because ViewHolders could be recycled and in the code above we could be trying to create a binding instance from a view that's already bound.

    Instead create the binding instance in initialisation block of the ViewHolder (this can be in init{} block or just after the class declaration as shown below)

    class BindingHolder(view: View): RecyclerView.ViewHolder(view) {
        val binding = ItemSampleBinding.bind(view)
    
        fun bindItem(item: Any) {
            //Rest of ViewHolder logic
            //binding.textView.text = "Something nice"
        }
    }
    

提交回复
热议问题