Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A collection of TexView extension functions (justify fun for now)
import android.text.Spanned
import android.text.style.ImageSpan
import android.graphics.drawable.ColorDrawable
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.widget.TextView
import java.util.concurrent.atomic.AtomicBoolean
fun TextView.justify() {
val isJustify = AtomicBoolean(false)
val textString = this.text.toString()
val textPaint = this.paint
val builder = SpannableStringBuilder()
this.post {
if (!isJustify.get()) {
val lineCount = this.lineCount
val thisWidth = this.width
for (i in 0 until lineCount) {
val lineStart = this.layout.getLineStart(i)
val lineEnd = this.layout.getLineEnd(i)
val lineString = textString.substring(lineStart, lineEnd)
if (i == lineCount - 1) {
builder.append(SpannableString(lineString))
break
}
val trimSpaceText = lineString.trim { it <= ' ' }
val removeSpaceText = lineString.replace(" ".toRegex(), "")
val removeSpaceWidth = textPaint.measureText(removeSpaceText)
val spaceCount = (trimSpaceText.length - removeSpaceText.length).toFloat()
val eachSpaceWidth = (thisWidth - removeSpaceWidth) / spaceCount
val spannableString = SpannableString(lineString)
for (j in 0 until trimSpaceText.length) {
val c = trimSpaceText[j]
if (c == ' ') {
val drawable = ColorDrawable(0x00ffffff)
drawable.setBounds(0, 0, eachSpaceWidth.toInt(), 0)
val span = ImageSpan(drawable)
spannableString.setSpan(span, j, j + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
builder.append(spannableString)
}
this.text = builder
isJustify.set(true)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.