Android TextView利用measureText自适应文本字体大小宽度

本是古典 何须时尚 2023-10-17 19:03 106阅读 0赞

Android TextView利用measureText自适应文本字体大小宽度

常常有这种情况,UI设计师限定一个文本TextView的宽度值比如80dip,但是该文本长度很长,于是造成文本不能正常显示,针对这种长文本长度超过TextView自身限定宽度的情况,需要把字体大小自适应的调整小。例如xml写了两个同样宽度为80dp的TextView,

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical">
  6. <TextView
  7. android:layout_width="80dp"
  8. android:layout_height="wrap_content"
  9. android:background="@android:color/holo_blue_bright"
  10. android:gravity="center"
  11. android:maxLines="1"
  12. android:text="zhangphil csdn"
  13. android:textSize="16dp" />
  14. <TextView
  15. android:id="@+id/text"
  16. android:layout_width="80dp"
  17. android:layout_height="wrap_content"
  18. android:background="@android:color/holo_blue_bright"
  19. android:gravity="center"
  20. android:maxLines="1"
  21. android:text="zhangphil csdn"
  22. android:textSize="16dp" />
  23. </LinearLayout>

设定textSize为16dp,显示内容是“zhangphil csdn”,但是明显,80dp宽度的TextView无法完全显示完整的“zhang phil”,所以需要调整字体大小。

  1. setContentView(R.layout.text);
  2. TextView text = findViewById(R.id.text);
  3. //获取80dp转换后的设备pix值。
  4. int mTextViewWidth = dip2px(this, 80);
  5. while (true) {
  6. //计算所有文本占有的屏幕宽度(pix)
  7. float textWidth = text.getPaint().measureText(text.getText().toString());
  8. //如果所有文本的宽度超过TextView自身限定的宽度,那么就尝试迭代的减小字体的textSize,直到不超过TextView的宽度为止。
  9. if (textWidth > mTextViewWidth) {
  10. int textSize = (int) text.getTextSize();
  11. textSize = textSize - 2;
  12. text.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
  13. } else {
  14. break;
  15. }
  16. }
  17. Log.d(TAG, "自适应字体的最终大小:" + text.getTextSize() + " pix");

运行输出:

  1. 04-11 09:36:03.404 29120-29120/zhangphil.test D/测试输出: 自适应字体的最终大小:34.0 pix

原理是先获得给定TextView的宽度(单位:px),如果所有文本累计的宽度超过TextView的宽度,那么久迭代的依次递减字体的textSize,试出合适的textSize为止。最终达到了自适应,限定宽度为80dp的TextView,自适应的把完整的文本装进去。作为对比,最上面的TextView没做任何自适应调整,文本就没法显示完全,少了“csdn”:

20180411094851479

工具方法dip2px:

  1. public static int dip2px(Context context, float dpValue) {
  2. final float scale = context.getResources().getDisplayMetrics().density;
  3. return (int) (dpValue * scale + 0.5f);
  4. }

发表评论

表情:
评论列表 (有 0 条评论,106人围观)

还没有评论,来说两句吧...

相关阅读