TextViewCompat自动调整大小功能无法在8.0之前的Android OS中使用

时间:2019-01-09 21:30:18

标签: android android-appcompat

我正在尝试使用textview自动调整大小。我的应用程序需要支持Android 6.0向前版本,因此我需要使用支持库,因为直到8.0才添加了自动调整大小的文本视图。我需要以编程方式进行。我尝试关注this answer。现在,我的代码如下:

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)

在更新的Android版本中,它看起来像我想要的样子:

enter image description here

但是在旧版本中,它很混乱:

enter image description here

1 个答案:

答案 0 :(得分:2)

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.