如何根据设备宽度和字体大小测量 TextView 高度? [英] How to Measure TextView Height Based on Device Width and Font Size?

查看:27
本文介绍了如何根据设备宽度和字体大小测量 TextView 高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找 Android 中的方法,该方法将接受输入(文本、text_font_size、device_width)并根据这些计算返回显示特定文本所需的高度?

I am looking for method in Android that will take a input (text, text_font_size, device_width) and based on these calculations it will return how much height will required to display particular text ?

我正在根据他的内容设置文本视图/网络视图高度运行时,我知道扭曲内容,但由于某些网络视图最小高度问题,我无法在我的情况下使用.

I am setting a text view/ webview height runtime based on his content,I am aware about warp content but I can't use in my case because of some web view minimum height issue.

所以我正在尝试计算高度并基于此设置视图高度.

So I am trying to calculate height and based on that I am setting view height.

我尝试了以下方法

Paint paint = new Paint();
paint.setTextSize(text.length()); 
Rect bounds = new Rect();
paint.getTextBounds(text, 0, 1, bounds);
mTextViewHeight= bounds.height();

所以输出是

1) "Hello World" 返回字体 15 的高度 13

1) "Hello World" returns a height of 13 for font 15

2) 最新版本的 Jelly Bean 来了,有性能优化"返回字体 15 的高度 16

2) "The latest version of Jelly Bean is here, with performance optimizations" returns a height 16 for font 15

然后我试过

Paint paint = new Paint();
paint.setTextSize(15);
paint.setTypeface(Typeface.SANS_SERIF);
paint.setColor(Color.BLACK);

Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), result);

Paint.FontMetrics metrics = brush.getFontMetrics();
int totalHeight = (int) (metrics.descent - metrics.ascent + metrics.leading);

所以输出是

1) "Hello World" 为字体 15 返回高度为 17

1) "Hello World" returns a height of 17 for font 15

2) 最新版本的 Jelly Bean 在这里,具有性能优化"返回字体 15 的高度 17

2) "The latest version of Jelly Bean is here, with performance optimisations" returns a height of 17 for font 15

如果我将这些值设置为我的视图,那么它会剪切一些文本,而不是显示所有内容.

if I set these values to my view then its cutting some text, its not showing all content.

同样,它在某些桌子上看起来还可以,因为它的宽度很大,但在手机上则不然.

Again it looks OK on some tables as its having big width but not on phone.

有没有办法根据内容计算高度?

Is there any way to calculate height based on content ?

推荐答案

public static int getHeight(Context context, String text, int textSize, int deviceWidth) {
    TextView textView = new TextView(context);
    textView.setText(text);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
    int widthMeasureSpec = MeasureSpec.makeMeasureSpec(deviceWidth, MeasureSpec.AT_MOST);
    int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    textView.measure(widthMeasureSpec, heightMeasureSpec);
    return textView.getMeasuredHeight();
}

如果 textSize 没有以像素为单位给出,则更改 setTextSize() 的第一个参数.

If textSize is not given in pixels, change the first paramter of setTextSize().

这篇关于如何根据设备宽度和字体大小测量 TextView 高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆