Skip to content

Instantly share code, notes, and snippets.

@truedem
Created April 19, 2022 06:35
Show Gist options
  • Save truedem/ba31bc5ca2bb396a2d1503cb59da2c1d to your computer and use it in GitHub Desktop.
Save truedem/ba31bc5ca2bb396a2d1503cb59da2c1d to your computer and use it in GitHub Desktop.
EditText extention to auto-resize fonts (+ in other fields) if the text is too long
package com.utils.texts
import android.graphics.Paint
import android.graphics.Rect
import android.text.Editable
import android.text.TextWatcher
import android.util.TypedValue
import android.widget.EditText
import kotlin.math.max
import kotlin.math.min
import androidx.core.widget.doAfterTextChanged
// usage in onCreate with edit text:
// binding.editText.autocorrectSize() { size ->
// binding.altText.setTextSize(TypedValue.COMPLEX_UNIT_PX, size)
// binding.altOtherText.setTextSize(TypedValue.COMPLEX_UNIT_PX, size)
// }
fun EditText.autocorrectSize(callback: ((Float) -> Unit)? = null) {
val originalTextSize = textSize
val bounds = Rect()
val paintForSearch = Paint()
paintForSearch.typeface = paint.typeface
paintForSearch.strokeWidth = paint.strokeWidth
paintForSearch.isAntiAlias = true
paintForSearch.textSize = paint.textSize
doAfterTextChanged {
val txt = it.toString()
if (width > 0) {
val minCorrection = width - originalTextSize / 2
paintForSearch.getTextBounds(txt, 0, txt.length, bounds)
if (bounds.width() > minCorrection) {
do {
paintForSearch.getTextBounds(txt, 0, txt.length, bounds)
if (bounds.width() > minCorrection) {
paintForSearch.textSize = max(paintForSearch.textSize - 1f, 10f)
}
} while (bounds.width() > minCorrection)
} else if (originalTextSize > paintForSearch.textSize) {
do {
paintForSearch.getTextBounds(txt, 0, txt.length, bounds)
if (bounds.width() < minCorrection) {
paintForSearch.textSize = min(paintForSearch.textSize + 1f, originalTextSize)
}
} while (bounds.width() < minCorrection && paintForSearch.textSize < originalTextSize)
}
}
setTextSize(TypedValue.COMPLEX_UNIT_PX, paintForSearch.textSize)
callback?.invoke(paintForSearch.textSize)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment