从 recyclerview 获取 TextView 字符串

Get TextView string from recyclerview

Recyclerview 包含从数据库中获取的三个文本视图(名称、电子邮件、phone)的卡片布局。如果 cardlayout 包含的名称等于某个字符串,我想从 recyclerview 中隐藏它。我尝试的是从数据库中获取数据后,我使用 if 语句将名称与字符串进行比较,如果它们相等,它们会使卡片布局不可见。但如果条件满足

,许多卡片布局会变得不可见
 if (dealer.getName().equals("abcde"))
     cardlayout.setVisibility(View.GONE);
       

在我看来,您的 RecyclerView 项目有多个项目 visibility of Gone

而且我确定您在 onBindViewHolder()RecyclerView.Adapter

中执行了该逻辑

你为什么会这样?

onBindViewHolder() 在项目为 init 时与该项目一起调用,当您滚动到另一个位置时,您不再看到该项目并滚动回该项目位置。

在 RecyclerView.Adapter 文档中,Google 说 onBindViewHolder():

Called by RecyclerView to display the data at the specified position. This method should update the contents of the RecyclerView.ViewHolder.itemView to reflect the item at the given position.

you should only use the position parameter while acquiring the related data item inside this method and should not keep a copy of it.

因此,当您重新滚动它之前或之后的项目时,并且您没有为您的项目设置 else case,那么它之前或之后的项目的值在 onBindViewHolder 将使您的内容返回到您设置卡片布局隐藏逻辑的项目上。

如何解决问题?

对于在 onBindViewHolder() 中显示或修改视图项的隐藏逻辑,请确保如果您有案例 if,那么您有案例 else

YourRecyclerViewAdapter.kt

override fun onBindViewHolder(holder: YourViewHolder, position: Int) {
    ...
    if (dealer.name == "abcde") {
        cardLayout.visibility = View.GONE
    } else { // You should have else case to return the correct content for other positions
        cardLayout.visibility = View.VISIBLE
    }
    ...
}