Get the size of a text in TextView

假装没事ソ 提交于 2019-11-27 18:58:23
Sherif elKhatib

If your textview is called TV

TV.setText("bla");
TV.measure(0, 0);       //must call measure!
TV.getMeasuredHeight(); //get height
TV.getMeasuredWidth();  //get width

More on this (updated): How to get width/height of a View

Midverse Engineer
Rect bounds = new Rect();

textView.getPaint().getTextBounds(textView.getText().toString(), 0, textView.getText().length(), bounds);

bounds.width() will give you the accurate width of the text in the Text View.

For some reason the solution of Midverse Engineer does not give me always correct results (at least on some Android versions). The solution of Sherif elKhatib works, but has the side effect of changing MeasuredWidth and Height. This could lead to incorrect positioning of the textView.

My solution:

width = textView.getPaint().measureText(text);
metrics = textView.getPaint().getFontMetrics();
height = metrics.bottom - metrics.top;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!