TextViewCompat 自动调整大小在 8.0 之前的 Android OS 中不起作用
TextViewCompat autoresizing not working in Android OS before 8.0
我正在尝试使用文本视图自动调整大小。我的应用程序需要支持 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 版本中,它看起来像我想要的那样:
但在旧版本中它搞砸了:
您应该使用 AppCompatTextView
,而不是正常的 TextView
。
看看 TextViewCompat method 是如何工作的:
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);
}
}
它适用于 8.1 或更高版本上的任何 TextView,因为它是在那时添加到框架中的。但是在任何其他 API 级别上,传递的 TextView 需要实现 AutoSizeableTextView 接口,而原生 TextView class 不会。
我正在尝试使用文本视图自动调整大小。我的应用程序需要支持 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 版本中,它看起来像我想要的那样:
但在旧版本中它搞砸了:
您应该使用 AppCompatTextView
,而不是正常的 TextView
。
看看 TextViewCompat method 是如何工作的:
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);
}
}
它适用于 8.1 或更高版本上的任何 TextView,因为它是在那时添加到框架中的。但是在任何其他 API 级别上,传递的 TextView 需要实现 AutoSizeableTextView 接口,而原生 TextView class 不会。