您现在的位置是:首页 > 文章详情

Android谷歌官方的自适应TextView字体大小的解决方案

日期:2018-04-13点击:438

Android谷歌官方的自适应TextView字体大小的解决方案

有时候UI限定了TextView宽度或者布局的控件空间尺寸不足,而此时的TextView里面的文本就无法完全正常显示。自适应TextView文本大小字体以适应限定宽度的TextView有不少方法,现在给出一种Android官方的自适应字体方法,直接在xml即可自适应。

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="80dp" android:layout_height="wrap_content" android:background="@android:color/holo_blue_bright" android:gravity="center" android:maxLines="1" android:text="zhang phil @ csdn" android:textColor="@android:color/white" android:textSize="80dp" /> <TextView android:id="@+id/text" android:layout_width="80dp" android:layout_height="wrap_content" android:autoSizeMaxTextSize="80dp" android:autoSizeMinTextSize="2dp" android:autoSizeTextType="uniform" android:background="@android:color/holo_red_light" android:gravity="center" android:maxLines="1" android:text="zhang phil @ csdn" android:textColor="@android:color/white" android:textSize="80dp" /> </LinearLayout> 


输出结果:


目标是完整显示“zhang phil @ csdn”字符串,两个TextView都特意把字体大小和TextView的宽度均设为80dp(故意制造无法完整显示完全的情景)。作为对比,蓝色的TextView没有做自适应处理,导致“zhang phil @ csdn”只能显示一个“z”,而红色的做自适应处理,能自适应的缩小字体完整的显示全部文本“zhang phil @ csdn”。

关键代码:

 android:autoSizeMaxTextSize="80dp" android:autoSizeMinTextSize="2dp" android:autoSizeTextType="uniform"

注意要把属性maxLines设置为1,否则可能会换行。


附录:
1,《Android TextView利用measureText自适应文本字体大小宽度》链接:https://blog.csdn.net/zhangphil/article/details/79891765

原文链接:https://yq.aliyun.com/articles/615696
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章