[Android] TextViewのフォントサイズ適応方法

バックグラウンド

ご存知のとおり、同じ単語でも中国語環境と英語環境では文字の長さが異なります。TextView がそれに応じて調整されていない場合、環境を切り替えた後に XML 内のテキストを読み取ると、UI が変更されます。特に英語の文章は中途半端な問題が出やすいです。

解決

Android 8以降では、TextViewのフォントサイズを動的に変更する新機能Autosizing TextViewsが追加されており、プロパティを設定するだけで済みます。
例えば:


    <TextView
        android:layout_width="340dp"
        android:layout_height="50dp"
        android:background="@drawable/shape_bg_008577"
        android:gravity="center_vertical"
        android:maxLines="1"
        android:text="这是标题,该标题的名字比较长,产品要求不换行全部显示出来"
        android:textSize="18sp"
        android:autoSizeTextType="uniform"
        android:autoSizeMaxTextSize="18sp"
        android:autoSizeMinTextSize="10sp"
        android:autoSizeStepGranularity="1sp"/>

焦点は、android:autoSizeTextType="uniform"自己適応ファイルを開始する
方法の特定のコメントにあります。

  <!-- Specify the type of auto-size. Note that this feature is not supported by EditText,
        works only for TextView. -->
        <attr name="autoSizeTextType" format="enum">
            <!-- No auto-sizing (default). -->
            <enum name="none" value="0" />
            <!-- Uniform horizontal and vertical text size scaling to fit within the
            container. -->
            <enum name="uniform" value="1" />
        </attr>
        <!-- Specify the auto-size step size if <code>autoSizeTextType</code> is set to
        <code>uniform</code>. The default is 1px. Overwrites
        <code>autoSizePresetSizes</code> if set. -->
        <attr name="autoSizeStepGranularity" format="dimension" />
        <!-- Resource array of dimensions to be used in conjunction with
        <code>autoSizeTextType</code> set to <code>uniform</code>. Overrides
        <code>autoSizeStepGranularity</code> if set. -->
        <attr name="autoSizePresetSizes"/>
        <!-- The minimum text size constraint to be used when auto-sizing text. -->
        <attr name="autoSizeMinTextSize" format="dimension" />
        <!-- The maximum text size constraint to be used when auto-sizing text. -->
        <attr name="autoSizeMaxTextSize" format="dimension" />
        <!-- Mode for justification. -->

ここに画像の説明を挿入
ナゲッツ参考
公式サイト参考

おすすめ

転載: blog.csdn.net/weixin_44002043/article/details/128833267