View must have a tag error in android data binding

前端 未结 7 2265
清酒与你
清酒与你 2021-02-13 05:54

I\'ve two layouts for a screen. Activity works fine while setting a layout for Mobile device but it\'s causing error while setting layout for tablet device. The main issue is:

7条回答
  •  孤城傲影
    2021-02-13 06:05

    I was having this problem when using an array adapter, having a crash due to a missing tag on convertView. In my getView(), I was doing:

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        if (convertView == null) {
            DataBindingUtil.inflate(
                LayoutInflater.from(parent.context),
                R.layout.item_spinner_drop_down_work_package_filter,
                parent,
                false
            )
        } else {
            binding = ItemSpinnerDropDownWorkPackageFilterBinding.bind(convertView) 
            binding.text1.setText(getItem(position))
            setDividerVisibility(binding.divider, position)
            return convertView
        }    
    
    }
    

    Which was crashing. The solution was to set the tag on the first run through getView:

     override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val binding = if (convertView == null) {
            DataBindingUtil.inflate(
                LayoutInflater.from(parent.context),
                R.layout.item_spinner_drop_down_work_package_filter,
                parent,
                false
            )
        } else {
            convertView.tag as ItemSpinnerDropDownWorkPackageFilterBinding
        }
        binding.text1.setText(getItem(position))
        setDividerVisibility(binding.divider, position)
        binding.root.tag = binding
        return binding.root
    
    }
    

提交回复
热议问题