androidgettextviewautosizetext-size

Android: How to get the actual textsize of an auto-sized TextView, in Kotlin?


It is sometimes desirable to set the same textSize for several auto-sized TextViews. For example, the "units" TextViews beside the "number input" EditTexts.

However, currently the auto-sizing in Android doesn't seem to have provided this functionality. So it's likely that we should write some function(s) to do this programmatically.

And the first step is to get actual textSize of an auto-sized TextView.

I tried:
val view = findViewById<TextView>(R.id.textView)
Toast.makeText(this, "text size is ${view.textSize}", Toast.LENGTH_LONG).show()

and changed to several locales on a phone.

The text size DID change for different locales, but the toasted message showed the same size (56.0).

How to get the actual textSize of an auto-sized TextView, in Kotlin?


Solution

  • Although this question was posted 10 months ago, I share my approach here to help those who might need it.

    For example, to get the actual textSize of TextView2 after autosizing, and set the textSize of TextView to that size, you can use the following code:

    override fun onCreate(...) {
        resetTextSize()
    }
    
    private fun resetTextSize(){
        binding.textView2.post{
            val textSizeRetrieved = binding.textView2.textSize
            binding.textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSizeRetrieved)
        }
    }