Home > OS >  Get TextView string from recyclerview
Get TextView string from recyclerview

Time:09-22

Recyclerview contain cardlayout with three textviews(name, email, phone) fetched from database. I want to hide the cardlayout from the recyclerview if it contains name equal to certain string. What i tried is after fetching data from database, i used if statement to compare name with string and if it's equal them make the cardlayout invisible. but many cardlayout are getting invisible if condition satisfy

 if (dealer.getName().equals("abcde"))
     cardlayout.setVisibility(View.GONE);
       

CodePudding user response:

It looks to me like your RecyclerView items are having multiple items with visibility of Gone.

And I'm sure you're doing that logic in onBindViewHolder() in RecyclerView.Adapter

Why are you in such a situation?

onBindViewHolder() is called with that item when the item is init , and when you scroll to another position you don't see that item anymore and scroll back to that item position.

In the RecyclerView.Adapter documentation, Google says about 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.

And

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

For this reason, When you re-scroll the item before it or after it, and you don't set an else case for your item, then the value of the item before it or after it in onBindViewHolder will get your content back on the item where you set the cardlayout hidden logic.

How to solve the problem?

For hidden logic that shows or modifies view items in onBindViewHolder(), make sure that if you have case if you have case 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
    }
    ...
}
  • Related