This is a quite common issue, we ran into in multiple apps we develop. Design requires that if the text is longer than a few lines, then we should add 3 dots, and the text ‘read more’, on which the user can click, where it then displays ‘read less’, to collapse again
There are quite some solutions floating around, but they all have a few flaws. They:
- can’t handle newlines inside the text
- don’t put the read more text at the end of the line, but at a random place in the last line. When you have a lot of list items below each other, this seems quite annoying
- they all use a layout listener. This means that they first layout the text, and then calculate the positions, which results in a second layout. This is unnecessary and the jumping is also visible for the user. If you are scrolling down fast, this is easily noticeable.
My solution is quite long because it has to handle these edge cases. Also, it uses TextLayout to do all the calculations, so it can be synchronous and can calculate the text so set immediately.
Add this to your code, and then create the strings resizable_text_read_more and resizable_text_read_less. (for example: “… read more”, and “read less”)
Now go to the place where you want to set the shortened text on the TextView.
textView.setResizableText(longText, 4, false)
You can replace ‘4’ with the max. amount of lines you want to see, before the ‘…read more’ gets added.