【已解决】 RecycleView中使用了View Binding
如果在RecycleView中用了View Binding,且适配器中的InnerHodler传的也是***Binding文件,导致数据绑定中用Glide加载网络图片拿不到context,该如何解决?
package com.example.myapplication.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.myapplication.databinding.ItemOnSellBinding
import com.example.myapplication.domain.OnSellData
class OnSellListAdapter :RecyclerView.Adapter<OnSellListAdapter.InnerHolder>() {
private val mContentList = arrayListOf<OnSellData.TbkDgOptimusMaterialResponse.ResultList.MapData>()
//第一步使用binding class 作为 root layout
class InnerHolder(binding: ItemOnSellBinding):RecyclerView.ViewHolder(binding.root) {
val title = binding.itemTitleTv
val offPriceTv = binding.offPriseTv
val itemCoverIv = binding.itemCoverIv
}
//第二步,inflate内容返回InnerHolder
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InnerHolder {
val binding= ItemOnSellBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return InnerHolder(binding)
}
//第三步,使用控件
override fun onBindViewHolder(holder: InnerHolder, position: Int) {
val data = mContentList[position]
holder.title.text=data.title
holder.offPriceTv.text = String.format("¥%.2f",data.zk_final_price.toFloat() - data.coupon_amount)
val coverUrl = "https:$data.pict_url"
Glide.with().load(coverUrl).into(holder.itemCoverIv)
}
override fun getItemCount(): Int {
return mContentList.size
}
fun setData(it: List<OnSellData.TbkDgOptimusMaterialResponse.ResultList.MapData>) {
mContentList.clear()
mContentList.addAll(it)
notifyDataSetChanged()
}
}
其实你深挖下去 Glide 不过也是在你传入的 View 之上调用了它的 getContext() 方法,它获取的还是你 Activity 的 Context,所以挖到底 你使用的其实还是你 Activity 的 Context !
你还愁context
面试问你,一个程序有多少个context?
哈哈!!!
你的holder.offPriceTv.text.context没有么?
你的InnerHolder.itemView.context没有么?
多得去了,哈哈!!!