Skip to content

Instantly share code, notes, and snippets.

@truedem
Last active October 8, 2022 13:54
Show Gist options
  • Save truedem/e38cb4cce3db1855c965190bf5e860fb to your computer and use it in GitHub Desktop.
Save truedem/e38cb4cce3db1855c965190bf5e860fb to your computer and use it in GitHub Desktop.
Auto-resizing EditText font with callback
// to change text size in related fields (like "+" in front of phone numbers or quasi-hint text in the field below):
// binding.textEdit.autocorrectSize { size ->
// binding.phoneCountryPrefixTextField.setTextSize(TypedValue.COMPLEX_UNIT_PX, size)
// binding.hintBelowInputTextField.setTextSize(TypedValue.COMPLEX_UNIT_PX, size)
// }
// or just myEditText.autocorrectSize() somewhere in onViewCreated()
fun EditText.autocorrectSize(callback: ((Float) -> Unit)? = null) {
val originalTextSize = this.textSize
val bounds = Rect()
val paintForSearch = Paint()
paintForSearch.typeface = paint.typeface
paintForSearch.strokeWidth = paint.strokeWidth
paintForSearch.isAntiAlias = true
paintForSearch.textSize = paint.textSize
doAfterTextChanged {
val actualText = it.toString()
if (width > 0) {
val minCorrection = width - originalTextSize / 2
paintForSearch.getTextBounds(actualText, 0, actualText.length, bounds)
if (bounds.width() > minCorrection) {
do {
paintForSearch.getTextBounds(actualText, 0, actualText.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(actualText, 0, actualText.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