Search code examples
androidandroid-recyclerviewandroid-custom-view

RecyclerView reusing variables inside custom view


I'm creating a custom ExpandableTextView to use in RecyclerView.

class ExpandableTextView : AppCompatTextView, View.OnClickListener {

    private var isCollapsed = true
    ...

The custom view itself works, but when used in a RecyclerView, the expanding state is also recycled with the ViewHolder. I suspect the var isCollapsed is reused too. How can I make RecyclerView display the TextView and its expanding state correctly? Can I make my variables not being reused?

Please help me to find some solutions. Any answer would be of great help!

Edit: I've added a gif to clarify. When I click on the first TextView, the last one also get expanded. Sorry I cannot post image yet!


Solution

  • Here is what you can do make the variable isCollapsed public so you can change it from outside

    class ExpandableTextView : AppCompatTextView, View.OnClickListener {
    
        var isCollapsed = true
        ...
    

    Your adapter

    override fun onBindViewHolder(viewHolder :YourViewHolder, position:Int) {
        viewHolder.expandleTextView.isCollapsed = true
    // Rest of your code
    }