Search code examples
androidtextviewandroid-textview-autosize

Can't change text size programmatically when using autosizing


I have multiple TextViews that use app:autoSizeTextType="uniform" and what I want to do is check which of those have the smallest text size after auto resize and then set that size to all other TextViews.

So I have method like this called from onCreate()

private fun setLabelsFontSize(){
    rootView.post {
        val minTextSize = minOf(textView1.textSize, textView2.textSize, textView3.textSize)

        textView1.setTextSize(TypedValue.COMPLEX_UNIT_PX, minTextSize)
        textView2.setTextSize(TypedValue.COMPLEX_UNIT_PX, minTextSize)
        textView3.setTextSize(TypedValue.COMPLEX_UNIT_PX, minTextSize)
    }
}

But nothing happens, text size stays the same. When I remove app:autoSizeTextType="uniform" from layout file then it works fine. How can I fix that


Solution

  • Call setTexSize like this:

    private fun setLabelsFontSize(){
        rootView.post {
            val minTextSize = minOf(textView1.textSize, textView2.textSize, textView3.textSize)
            TextViewCompat.setAutoSizeTextTypeWithDefaults(textView1, TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE)
            TextViewCompat.setAutoSizeTextTypeWithDefaults(textView2, TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE)
            TextViewCompat.setAutoSizeTextTypeWithDefaults(textView3, TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE)
            textView1.setTextSize(TypedValue.COMPLEX_UNIT_PX, minTextSize)
            textView2.setTextSize(TypedValue.COMPLEX_UNIT_PX, minTextSize)
            textView3.setTextSize(TypedValue.COMPLEX_UNIT_PX, minTextSize)
        }
    }