Skip to content

Instantly share code, notes, and snippets.

@glureau
Last active April 13, 2020 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glureau/22baba67dbf24952cfda922c659d0b23 to your computer and use it in GitHub Desktop.
Save glureau/22baba67dbf24952cfda922c659d0b23 to your computer and use it in GitHub Desktop.
/**********************************************************************************************************************
* Remapping auto-size functionalities from AppCompatTextViewAutoSizeHelper.
**********************************************************************************************************************/
fun AppCompatTextView.autoSizeTextAvailableSizes(): IntArray =
invokeAndReturnWithDefault(this, "getAutoSizeTextAvailableSizes", IntArray(0))
/**********************************************************************************************************************
* Copied from AppCompatTextViewAutoSizeHelper but adapted to AppCompatTextView.
**********************************************************************************************************************/
private fun <T> invokeAndReturnWithDefault(target: Any, methodName: String, defaultValue: T): T {
return try {
// Cache lookup.
getTextViewMethod(methodName)!!.invoke(target) as T
} catch (ex: Exception) {
Log.w(LOG_TAG, "Failed to invoke TextView#$methodName() method", ex)
defaultValue
}
}
/**********************************************************************************************************************
* Copied from AppCompatTextViewAutoSizeHelper but adapted to AppCompatTextView.
**********************************************************************************************************************/
// Cache of TextView methods used via reflection; the key is the method name and the value is
// the method itself or null if it can not be found.
private val sTextViewMethodByNameCache = ConcurrentHashMap<String, Method>()
private fun getTextViewMethod(methodName: String): Method? {
try {
var method: Method? = sTextViewMethodByNameCache[methodName]
if (method == null) {
method = AppCompatTextView::class.java.getDeclaredMethod(methodName)
if (method != null) {
method.isAccessible = true
// Cache update.
sTextViewMethodByNameCache[methodName] = method
}
}
return method
} catch (ex: Exception) {
Log.w(LOG_TAG, "Failed to retrieve TextView#$methodName() method", ex)
return null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment