天天看点

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

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

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

<?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="zhangphil csdn"
        android:textSize="16dp" />

    <TextView
        android:id="@+id/text"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_blue_bright"
        android:gravity="center"
        android:maxLines="1"
        android:text="zhangphil csdn"
        android:textSize="16dp" />
</LinearLayout>           

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

setContentView(R.layout.text);
        TextView text = findViewById(R.id.text);

        //获取80dp转换后的设备pix值。
        int mTextViewWidth = dip2px(this, 80);

        while (true) {
            //计算所有文本占有的屏幕宽度(pix)
            float textWidth = text.getPaint().measureText(text.getText().toString());

            //如果所有文本的宽度超过TextView自身限定的宽度,那么就尝试迭代的减小字体的textSize,直到不超过TextView的宽度为止。
            if (textWidth > mTextViewWidth) {
                int textSize = (int) text.getTextSize();
                textSize = textSize - 2;
                text.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
            } else {
                break;
            }
        }

        Log.d(TAG, "自适应字体的最终大小:" + text.getTextSize() + " pix");           

运行输出:

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

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

工具方法dip2px:

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

继续阅读