Created
March 10, 2021 12:42
-
-
Save CompileConnected/393f3724d9a8724b2da297651367d132 to your computer and use it in GitHub Desktop.
Make show/hide TextView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| fun TextView.showMoreClickable( | |
| showText: String = "Show More", | |
| hideText: String = "Show Less", | |
| showTextClickListener: View.OnClickListener? = null, | |
| hideTextClickListener: View.OnClickListener? = null, | |
| hideCharacterAtEndOf: Int = 200, | |
| hideCharacterAtEndLineOf: Int = 3 | |
| ) { | |
| this.doOnPreDraw { | |
| val text = this.text?.toString() | |
| var result = this.text?.toString() | |
| var hideable = false | |
| val ll = (it as TextView).lineCount | |
| if (ll > hideCharacterAtEndOf) { | |
| val endIndex = layout.getLineEnd((hideCharacterAtEndLineOf - 1)) | |
| result = text?.substring(0, endIndex) ?: "" | |
| hideable = true | |
| } else if ((text?.length ?: 0) > hideCharacterAtEndOf) { | |
| result = text?.substring(0, hideCharacterAtEndOf) ?: "" | |
| hideable = true | |
| } | |
| if (hideable) { | |
| val tempShowText = SpannableString("$result $showText") | |
| val tempHideText = SpannableString("$text $hideText") | |
| tempHideText.setSpan( | |
| object : ClickableSpan() { | |
| override fun onClick(widget: View) { | |
| widget.invalidate() | |
| [email protected](tempShowText, TextView.BufferType.SPANNABLE) | |
| hideTextClickListener?.onClick(widget) | |
| } | |
| }, | |
| tempHideText.lastIndex - hideText.lastIndex, | |
| tempHideText.length, | |
| Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | |
| ) | |
| tempShowText.setSpan( | |
| object : ClickableSpan() { | |
| override fun onClick(widget: View) { | |
| widget.invalidate() | |
| [email protected](tempHideText, TextView.BufferType.SPANNABLE) | |
| showTextClickListener?.onClick(widget) | |
| } | |
| }, | |
| tempShowText.lastIndex - showText.lastIndex, | |
| tempShowText.length, | |
| Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | |
| ) | |
| this.movementMethod = LinkMovementMethod.getInstance() | |
| this.setText(tempShowText, TextView.BufferType.SPANNABLE) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment