2

I am trying to use textview autosizing. My app needs to support Android 6.0 forward, so I needed to use the Support library because the autosize textview was not added until 8.0. I need to do it programatically. I tried following this answer. Right now my code looks like this:

val label = TextView(context)
label.text = i.label
val value = TextView(context)
value.text = i.valueFormatted
value.textSize = 48f
label.textSize = 36f

TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(value, 1, 48, 1, TypedValue.COMPLEX_UNIT_DIP)
TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(label, 1, 24, 1, TypedValue.COMPLEX_UNIT_DIP)

In newer Android versions it looks like how I want it:

enter image description here

But in old versions it's messed up:

enter image description here

clavio
  • 1,022
  • 1
  • 16
  • 34

1 Answers1

6

You should be using AppCompatTextView, not the normal TextView.

Take a look at how that TextViewCompat method works:

public static void setAutoSizeTextTypeUniformWithConfiguration(
        @NonNull TextView textView,
        int autoSizeMinTextSize,
        int autoSizeMaxTextSize,
        int autoSizeStepGranularity,
        int unit) throws IllegalArgumentException {
    if (Build.VERSION.SDK_INT >= 27) {
        textView.setAutoSizeTextTypeUniformWithConfiguration(
                autoSizeMinTextSize, autoSizeMaxTextSize, autoSizeStepGranularity, unit);
    } else if (textView instanceof AutoSizeableTextView) {
        ((AutoSizeableTextView) textView).setAutoSizeTextTypeUniformWithConfiguration(
                autoSizeMinTextSize, autoSizeMaxTextSize, autoSizeStepGranularity, unit);
    }
}

It'll work for any TextView on 8.1 or later, because that's when it was added to the framework. But on any other API level, the TextView passed needs to implement the AutoSizeableTextView interface, which the native TextView class doesn't do.

TheWanderer
  • 16,775
  • 6
  • 49
  • 63