RecycleView列表项目不出现
我一直在尝试使RecyclerView
在我的应用程序中工作,其中的列表项是ImageView
,并且图像被下载并放入(异步)在onBindViewHolder
方法中。 我没有在我的代码中遇到任何错误,但出于某种原因
只有在活动加载时才会显示(甚至部分)给用户的列表项,将图像加载到其中。
虽然我看不到图像,但我发现这些项目的高度和宽度已经正确分配。 而且由于图像首先下载,然后确定ImageView
的尺寸,我认为这个问题与RecyclerView
本身有关系吗? 如果有人能够对此有所了解,那就太好了。 谢谢。
我还想补充一点,如果活动暂停,然后恢复(通过单击“方形”导航按钮,然后恢复),所有列表项的图像加载正确。
图#1 图#2
这是我的代码:
onCreate
方法:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) recyclerView { id = ViewID.ID_LIST } val imgList = ArrayList<ImageView>() imgList.add(ImageView(ctx)) imgList.add(ImageView(ctx)) imgList.add(ImageView(ctx)) imgList.add(ImageView(ctx)) val lv = findViewById(ViewID.ID_LIST) as RecyclerView lv.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) lv.adapter = ImageRecyclerAdapter(ctx, imgList) }
RecyclerView.Adapter
类:
private class ImageRecyclerAdapter(val context: Context, val imageList: ArrayList<ImageView>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun onViewRecycled(holder: RecyclerView.ViewHolder?) { super.onViewRecycled(holder) if (holder != null) { val v = holder.itemView as ImageView v.setImageBitmap(null) } } override fun onBindViewHolder(p: RecyclerView.ViewHolder, position: Int) { val v = p.itemView as ImageView Ion.with(v) .load("https://pbs.twimg.com/profile_images/616076655547682816/6gMRtQyY.jpg") .setCallback({ exception, t -> if (t != null) { val dm = Point() context.windowManager.defaultDisplay.getRealSize(dm) val w = t.maxWidth val h = t.maxHeight val params = t.layoutParams if (params != null) { params.width = dm.x params.height = (dm.x * (h.toDouble() / w.toDouble())).toInt() t.layoutParams = params t.requestLayout() } } }) } override fun getItemCount(): Int { return imageList.size } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder { val v = ImageView(context) return object : RecyclerView.ViewHolder(v) {} } }
它在将数据绑定到同步请求之后起作用,并将ImageView
操作(更改LayoutParams
)移动到适配器的onViewAttachedToWindow
重写方法中。
onViewAttachedToWindow
:
override fun onViewAttachedToWindow(holder: RecyclerView.ViewHolder?) { super.onViewAttachedToWindow(holder) val t = holder?.itemView as ImageView val dm = Point() context.windowManager.defaultDisplay.getRealSize(dm) val w = t.maxWidth val h = t.maxHeight val params = t.layoutParams if (params != null) { params.width = dm.x params.height = (dm.x * (h.toDouble() / w.toDouble())).toInt() t.layoutParams = params t.requestLayout() } }
onBindViewHolder
:
override fun onBindViewHolder(p: RecyclerView.ViewHolder, position: Int) { val v = p.itemView as ImageView Ion.with(v) .load(imageList[position].toString()) .tryGet() }