是否可以在 onBindViewHolder 之外使用 ViewHolder 元素?
这是我的适配器类
@SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = mValues[position]
with(holder.mView) {
tag = item
txvTitle.text = item.title
setOnClickListener(mOnClickListener)
}
}
inner class ViewHolder(val mView: View) :RecyclerView.ViewHolder(mView{})
如果我在适配器中有一个函数,我该如何使用 txvTitle
?
fun checkHashMapExists(hashMap: HashMap<Long, ABC>?, newValues: ArrayList<OT>){
for(i in newValues){
if(hashMap?.keys.toString().contains(i.id)){
txvTitle.setTextColor(Color.parseColor("#000000")) // txvTitle cannot resolved
}
}
}
fragment A
override fun onResume() {
super.onResume()
mAdapter.checkHashMapExists(hashMap,otList)
}
最佳答案
尽管我不建议使用它,但您可以调用以下方法来获取位置i
的数据元素的ViewHolder:
MyViewHolder holder = (MyViewHolder) mRecyclerView.findViewHolderForAdapterPosition(i);
if(holder != null) {
// Do whatever you want
}
请记住 documentation 是什么说到那个方法:
Return the
ViewHolder
for the item in the given position of the data set. UnlikefindViewHolderForLayoutPosition(int)
this method takes into account any pending adapter changes that may not be reflected to the layout yet. On the other hand, ifnotifyDataSetChanged()
has been called but the new layout has not been calculated yet, this method will return null since the new positions of views are unknown until the layout is calculated.
相反,如果我是你我会做什么,是在你的模型类中有一个属性,指示它的 ViewHolder 应该使用哪种颜色来显示 txtView.title
文本。
然后,每当您想更新 RecyclerView 中一个或多个元素的颜色时,您可以更改模型类的该属性,然后调用 notifyDataSetChanged();
关于android - 在 onBindViewHolder 之外使用 ViewHolder 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55618741/