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

Example
Example

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.

Daniel - Team - Egeniq

Written by Dániel Zolnai

Software Engineer
Usually, Dániel has already done the job before you have even asked him to start. And he always delivers top quality work. This has made him our in-house psychic. He does not do Toto-forecasts however, which is a bummer.

Share

Leave a comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.