AppCompatTextView它是Android標準TextView的增強:
AppCompatTextView最顯著的特點是可以自適應字體寬度大小變化。這個特點很有用,有些開發場景下,UI設計限定了一個文本的寬度,但是文本的長度可能比較長,如果設定一個固定的textSize,就導致一部分文本無法顯示。而AppCompatTextView就是爲此而生,設定三個參數就可以讓文本隨着文本寬度的變化,限定在一個固定範圍內完整顯示出來:
注意:是 app:autoSizeTextType=“uniform” 而不是 android:autoSizeTextType=“uniform”
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="50dp"
android:layout_height="wrap_content"
app:autoSizeMaxTextSize="18dp"
app:autoSizeMinTextSize="8dp"
app:autoSizeTextType="uniform"
android:maxLines="1"
android:text="林偉茂林偉茂"
android:textSize="18dp" />
在佈局裏面把過去的TextView換成AppCompatTextView,然後配置:
- app:autoSizeTextType=“uniform” ,即可自適應寬度。
- app:autoSizeMinTextSize=“8dp”,約束雖然可以自適應調整字體大小,但最小不能小於8dp。
- app: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上的一個開源項目:
me.grantland.widget.AutofitTextView
然而,AutofitTextView也很久沒有維護了。何況現在有了Android官方提供的支持,建議開發者以後可以使用AppCompatTextView用以支持字體的自適應大小變化。