Created
November 15, 2018 13:55
-
-
Save FireZenk/d166e5107bfa0d10ce68e1e040e967a4 to your computer and use it in GitHub Desktop.
A collection of TexView extension functions (justify fun for now)
This file contains 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
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