android - 在 onBindViewHolder 之外使用 ViewHolder 元素?

标签 android kotlin android-recyclerview

是否可以在 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. Unlike findViewHolderForLayoutPosition(int) this method takes into account any pending adapter changes that may not be reflected to the layout yet. On the other hand, if notifyDataSetChanged() 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/

相关文章:

android - 如何先按文本排序,然后按包含数字的文本排序

java - 在 Android 中从导入的 jar 中读取资源

java - WakefulBroadcastReceiver 无法解析为类型

kotlin - 如何从 kotlin 中的数据类访问 val?

android - 从 IntentService 添加数据时,recyclerview 崩溃

android - 从 RecyclerView 中检索每行的多个编辑文本

php - 从android设备上传文件到php服务器

kotlin - 我在 kotlin 安全调用中遇到重载解析歧义错误

android - 如何使用Kotlin DSL Gradle启用代码覆盖?

Android 回收器 View 行项目在滚动时重复,同时 View 扩展相对布局