How to use ViewBinding in a RecyclerView.Adapter?

前端 未结 7 2136
小鲜肉
小鲜肉 2021-02-05 01:59

Can I use ViewBindings to replace findViewById in this typical RecyclerView.Adapter initialization code? I can\'t set a binding val in the

7条回答
  •  心在旅途
    2021-02-05 02:27

    If you're ok with reflection, I have a much easier way to do this. Just call ViewGroup.toBinding() then you can get the binding object you want. But since we're talk about reflection, remember you have to modify your proguard-rule to make it work even for proguard.

    // inside adapter
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return MainViewHolder(parent.toBinding())
    }
    
    // ViewHolder
    class MainViewHolder(private val binding: AdapterMainBinding) :
        RecyclerView.ViewHolder(binding.root) {
    
        fun bind(data: String) {
            binding.name.text = data
        }
    }
    
    // The magic reflection can reused everywhere.
    inline fun  ViewGroup.toBinding(): V {
        return V::class.java.getMethod(
            "inflate",
            LayoutInflater::class.java,
            ViewGroup::class.java,
            Boolean::class.java
        ).invoke(null, LayoutInflater.from(context), this, false) as V
    }
    

    I put all this into an open source project you can take a look as well. Not only for Adapter usage but also include Activity and Fragment. And do let me know if you have any comment. Thanks.

    https://github.com/Jintin/BindingExtension

提交回复
热议问题