LoginSignup
28
26

More than 5 years have passed since last update.

AndroidのTextViewのフォントサイズを自動調整する

Posted at

経緯

iOSではかなり昔からあった(気がする)TextView系のフォントサイズ自動調整機能。
Androidでも当然オプションとしてあるだろーと調べてみると意外にもAndroid 8.0 (API level 26) から対応したとのこと。
割と最近の話じゃないかと思った&微妙にはまったのでメモ。

Autosizing TextViewsを使う

Android 8.0 (API level 26) からAutosizingTextViewが追加になりました。xmlにandroid:autoSizeTextTypeを追加します。

<TextView
    android:layout_width="match_parent" 
    android:layout_height="200dp"
    android:autoSizeTextType="uniform"
    app:autoSizeMinTextSize="12sp"
/>

計二回動かない問題にぶち当たりました。

駄目だったやつ

<TextView
    android:layout_width="wrap_content" 
    android:layout_height="200dp"
    android:autoSizeTextType="uniform"
/>

上記の問題点は二つです。
まずひとつめ、android:layout_widthにwrap_contentを指定していること。
公式にもちゃんと書いてあるのですが、wrap_conttentを使用する場合は期待通りに動かないかもね、らしいです。

Note: If you set autosizing in an XML file, it is not recommended to use the value "wrap_content" for the layout_width or layout_height attributes of a TextView. It may produce unexpected results.

そしてふたつめ、app:autoSizeMinTextSizeを指定していなかったこと。
これもそれとなーく公式に書いてあります。

Set autoSizeMinTextSize, autoSizeMaxTextSize, and autoSizeStepGranularity attributes to define the dimensions for the autosizing of TextView.

結論

リファレンスはちゃんと読みましょう。。。

おまけ(API26より以前のバージョンの対応の場合)

<android.support.v7.widget.AppCompatTextView
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:autoSizeTextType="uniform"
    app:autoSizeMinTextSize="12sp"
/>
あるならもっと早く対応してくれても良いのでは

参考

28
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
26