【问题标题】:ViewBinding.getRoot().getLayoutParams() always return nullViewBinding.getRoot().getLayoutParams() 总是返回 null
【发布时间】:2021-02-04 08:08:06
【问题描述】:

当我像这样在 RecyclerView.Adapter 中使用 ViewBinding 时:

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)
}

itemView1 的 layoutParams 始终为 null -- 忽略 xml 中的 attrs,itemView2&itemView3 的 layoutParams 工作正常。 那么这是 ViewBinding::inflate 的错误吗?

【问题讨论】:

    标签: android android-jetpack android-viewbinding


    【解决方案1】:

    布局参数来自父布局,如果你在没有父布局的情况下膨胀,就不会有布局参数。使用采用父布局的重载:

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

    (最好同时捕获绑定引用并且不要立即将其丢弃。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-04
      • 2016-11-02
      • 2014-05-06
      • 2012-06-05
      • 2014-05-30
      • 2014-02-23
      • 2017-10-12
      • 2013-08-16
      相关资源
      最近更新 更多