Android – Show more TextView

Tram Ho

Introduce

Above is a case you may encounter in Android UI programming. It’s a TextView that can expand and shrink content, with “Show more” and “Show less” buttons following right behind the content of TextView. The problem here is the calculation of the number of characters of the string will display in TextView with max lenght allowed, then calculate the length needed to add more dots and the text “Show more” / “Show less” to Add these components to the previously calculated rock sequence

Deployment

To accomplish this function, I will create a custom TextView First, read the full code of it, I will explain in detail below.

Here are the funtions to init the information of ShowMoreTextView

First, at init I will add an addOnGlobalLayoutListener to listen to the change of layout when TextView is setText to handle the new string.

When there is a change in text, the showMoreButton () function will be called if showingLine <lineCount (The number of lines of the string just set) the showMoreButton () function will be responsible for calculating and cutting the string that can be displayed with the current showingLine. then add a dot and a SpannableString “Show more” and finally setText the opposite for this TextView itself.

When the “Show more” button is clicked, it will call the showLessbutton () function: this function is simpler, just take the original string set and add Spannable “Show less”

Use

Use in Activity

Hope this article will be helpful to you, thanks for watching

Share the news now

Source : Viblo