Last active
April 13, 2020 20:19
-
-
Save glureau/22baba67dbf24952cfda922c659d0b23 to your computer and use it in GitHub Desktop.
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
/********************************************************************************************************************** | |
* 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