Skip to content

Instantly share code, notes, and snippets.

@CompileConnected
Created March 10, 2021 12:42
Show Gist options
  • Select an option

  • Save CompileConnected/393f3724d9a8724b2da297651367d132 to your computer and use it in GitHub Desktop.

Select an option

Save CompileConnected/393f3724d9a8724b2da297651367d132 to your computer and use it in GitHub Desktop.
Make show/hide TextView
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