Android textview realizes Click to display full text and hide functions (with source code)

preface

I believe that in daily development, you often encounter scenes where large sections of text need to be partially displayed. The usual practice is to add "display full text" at the end of the text in the hidden state and "hide" at the end of the text in the expanded state to control the display state of the text. There may be many implementation methods for this interaction. This paper uses a simple textview to implement these interactions. The encapsulated collapsiabletextview only adds less than 70 additional methods.

Parameter definition

As shown in the figure above, we need to use several configurable parameters:

These parameters represent

The main constructors are as follows:

Agent onclick event

To configure whether display and hide operations are triggered by suffixes, we need to handle click events in collapsibletextview. Therefore, set clicklistener to mclicklistener in the constructor. At the same time, click events are handled in mclicklistener:

In order that users can still set the clicklistener, we override the setonclicklistener method and leave the clicklistener as mcustomclicklistener:

This proxies the click event inside the collapsibletextview.

Clickablespan handles some text clicks

In order to be able to listen for postfix click events, you need to use clickablespan

Spannablestring is calculated based on the status

Among them, paint.measuretext can measure the width of the text layout, so as to obtain only the number of text lines, compare with mcollapsedlines, cut out the appropriate character length, add the suffix and span, and give textview

Since the value of getlineend and other functions is meaningful only after the layout process, it is necessary to reasonably select the timing of applystate:

So far, the key points of collapsibletextview have been completed. Add getter, setter function and some logical organization

Source code download: click here

summary

The above is the whole content of this article. I hope the content of this article can bring some help to Android developers. If you have any questions, you can leave a message. Thank you for your support for programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>