Search code examples
androidandroid-recyclerviewandroid-view

what lifecycle methods are called on a reusable element in a recyclerView?


I have a RecyclerView to which I pass text and want to understand the following: if lineCount > 3, then I show the expand button, set the ellipsize to end state and make maxLines = 3.

To do this I use a textView listener, something like this. I'm setting currentLineCount = textView.lineCount and causing other states to be set inside the listener such as maxLines etc

fun View.afterLayoutConfiguration(func: () -> Unit) {
     viewTreeObserver?.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
         override fun onGlobalLayout() {
             viewTreeObserver?.removeOnGlobalLayoutListener(this)
             func()
         }
     })
}

However, I'm running into a problem because the RecyclerView is reusing items and listening causes the state of the old views to be applied to new items when scrolling.

I need help understanding how to solve this case, because I haven’t found how to calculate the number of lines in a textview.


Solution

  • The goal was to find out whether my text was more than 3 lines or not. if yes, make the button visible and set the maximum number of lines to 3. The question was to understand the life cycle and install and remove the listener in time, but the solution with the listener for the number of lines is incorrect because the recyclerView carries bugs

    I ended up going down a different path. I decided to set the attributes android:ellipsize="end", android:maxLines="3" and then

    Text.post {
      val isEllipsizeApplied = TextUtils.equals(text, Text.layout.text).not()
      tvExpand.visibility = if (isEllipsizeApplied || isExpanded) View.VISIBLE else View.GONE
    }
    

    I hope this helps someone)