Android新增AppCompatTextView自适应字体大小和文本宽度

超、凢脫俗 2023-10-17 23:01 118阅读 0赞

Android新增AppCompatTextView自适应字体大小和文本宽度

Android的supportv7包中新增了一个AppCompatTextView,它是Android标准TextView的增强:

package android.support.v7.widget;

public class AppCompatTextView extends TextView implements TintableBackgroundView,
AutoSizeableTextView {

}

AppCompatTextView最显著的特点是可以自适应字体宽度大小变化。这个特点很有用,有些开发场景下,UI设计限定了一个文本的宽度,但是文本的长度可能比较长,如果设定一个固定的textSize,就导致一部分文本无法显示。而AppCompatTextView就是为此而生,设定三个参数就可以让文本随着文本宽度的变化,限定在一个固定范围内完整显示出来:

  1. <android.support.v7.widget.AppCompatTextView
  2. android:layout_width="wrap_content"
  3. android:layout_height="match_parent"
  4. android:autoSizeMinTextSize="8dp"
  5. android:autoSizeTextType="uniform"
  6. android:autoSizeMaxTextSize="18dp"
  7. android:maxLines="1"
  8. android:text="-.-"
  9. android:textSize="18dp" />

在布局里面把过去的TextView换成AppCompatTextView,然后配置:
android:autoSizeTextType=”uniform”
即可自适应宽度。
android:autoSizeMinTextSize=”8dp”,约束虽然可以自适应调整字体大小,但最小不能小于8dp。
android:autoSizeMaxTextSize=”18dp”,限定字体大小自适应调整变化时候,最大不能超过的数值。

需要注意的是,根据Android官方对AppCompatTextView的解释说:
/**
* A {@link TextView} which supports compatible features on older versions of the platform,
* including:
*


    *
  • Allows dynamic tint of its background via the background tint methods in
    * {@link android.support.v4.view.ViewCompat}.

  • *
  • Allows setting of the background tint using {@link R.attr#backgroundTint} and
    * {@link R.attr#backgroundTintMode}.

  • *
  • Supports auto-sizing via {@link android.support.v4.widget.TextViewCompat} by allowing
    * to instruct a {@link TextView} to let the size of the text expand or contract automatically
    * to fill its layout based on the TextView’s characteristics and boundaries. The
    * style attributes associated with auto-sizing are {@link R.attr#autoSizeTextType},
    * {@link R.attr#autoSizeMinTextSize}, {@link R.attr#autoSizeMaxTextSize},
    * {@link R.attr#autoSizeStepGranularity} and {@link R.attr#autoSizePresetSizes}, all of
    * which work back to
    * {@link android.os.Build.VERSION_CODES#ICE_CREAM_SANDWICH Ice Cream Sandwich}.

  • *

*
*

This will automatically be used when you use {@link TextView} in your layouts
* and the top-level activity / dialog is provided by
* appcompat.
* You should only need to manually use this class when writing custom views.


*/

这段文档中最后一段比较重要,Android官方提示开发者,如果开发者在xml布局中写了一个过去传统的Android的TextView,那么这个TextView会被自动被Android编译系统替换成AppCompatTextView。在在Android O(8.0)系统及以上,TextView和AppCompatTextView是相同的。在低于8.0的版本上,开发者可在自定义和布局中需要写文本View时候,可以使用AppCompatTextView,以使用到Android最新的自适应大小的特性。

在过去,没有AppCompatTextView官方这一自适应字体大小text view时候,开发者常常使用github上的一个开源项目:

  1. me.grantland.widget.AutofitTextView

然而,AutofitTextView也很久没有维护了。何况现在有了Android官方提供的支持,建议开发者以后可以使用AppCompatTextView用以支持字体的自适应大小变化。

发表评论

表情:
评论列表 (有 0 条评论,118人围观)

还没有评论,来说两句吧...

相关阅读