當一個元件所顯示的內容過長時,可能會顯得不完整。在Android 8 (Oreo, SDK 26)增加了自動調整字體大小,讓TextView文字大小自動擴展或收縮,使得輸入時可以看到完整內容。
Step 1: 畫面布局
首先我們先設定一個輸入框及所要顯示的內容,並且限制TextView的大小為100dp並且使用單行顯示。
activity_main.xml1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FF97BFFF" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_marginTop="88dp" android:text="Hello" android:textSize="18sp" android:maxLines="1" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
<EditText android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="28dp" android:ems="10" android:hint="Enter..." android:inputType="textPersonName" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.537" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> </androidx.constraintlayout.widget.ConstraintLayout>
|
在Android 8之前,如果我們輸入的文字超過此TextView的寬度時,會無法顯示完整內容。
Step 2: 設定AutoSize
在TextView的元件上增加android:autoSizeTextType=”uniform”, autoSizeTextType有兩種參數可設定,預設值為 none。
AUTO_SIZE_TEXT_TYPE_NONE (none):關閉自動調整功能。
AUTO_SIZE_TEXT_TYPE_UNIFORM (uniform):開啟自動調整功能。
activity_main.xml1 2 3 4 5 6 7 8 9 10 11 12 13
| <TextView android:id="@+id/textView" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_marginTop="88dp" android:text="Hello" android:textSize="18sp" android:maxLines="1" android:autoSizeTextType="uniform" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
|
執行結果
當輸入文字超過顯示框時,會自動調整字體大小