【译】Autosizing TextViews

/ 0评 / 1

Autosizing TextViews

在Android 8.0(API 26)及以上版本中,TextView能自适应文字大小,再也不用担心文字大小适配了,当然,从Support Library 26开始,也提供了低版本的适配,最低到Android 4.0,所以不用担心适配问题。

在XML中使用

如下。所示,autoSizeTextType取值为"none""uniform"代表是否自动缩放,autoSizeMinTextSize代表最小的文字大小,autoSizeMaxTextSize代表最大的文字大小,autoSizeStepGranularity代表当文字自动放大/缩小的时候文字大小变化的大小。

<?xml version="1.0" encoding="utf-8"?>
<TextView
    android:layout_width="match_parent"
    android:layout_height="200dp"
    app:autoSizeTextType="uniform"
    app:autoSizeMinTextSize="12sp"
    app:autoSizeMaxTextSize="100sp"
    app:autoSizeStepGranularity="2sp" />

当然我们也可以手动指定文字大小变化的区间

define the array in the res/values/arrays.xml file.

<resources>
  <array name="autosize_text_sizes">
    <item>10sp</item>
    <item>12sp</item>
    <item>20sp</item>
    <item>40sp</item>
    <item>100sp</item>
  </array>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<TextView
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:autoSizeTextType="uniform"
    android:autoSizePresetSizes="@array/autosize_text_sizes" />

通过代码设置

如下

//TextViewCompat#AUTO_SIZE_TEXT_TYPE_UNIFORM
//TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE
TextViewCompat.setAutoSizeTextTypeWithDefaults(mBinding.test, TextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE);

当然也可以指定最大/最小等

TextViewCompat.setAutoSizeTextTypeWithDefaults(tv,30, 50, 2, TypedValue.COMPLEX_UNIT_SP);

其他

当我们要使用自动缩放的时候,不能给TextView设置singleLine属性,不然会失效

https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注