I am new to Android.. I have a textview with size 250dp.. I am trying to calculate the text width inside it.. But I could not find any API that returns the actual content width.. Can someone help how it can be done. Thanks in advance.
-
possible duplicate of [Get the size of a text in TextView](http://stackoverflow.com/questions/6734301/get-the-size-of-a-text-in-textview) – Alex K Feb 20 '15 at 03:18
-
@alex.. Do you mean getMeasuredWidth() returns the actual content width? – user4582135 Feb 20 '15 at 03:51
3 Answers
You can use the Paint
object held by the TextView
to measure the width of the text contents:
CharSequence text = textView.getText();
float width = textView.getPaint().measureText(text, 0, text.length());
There is also a version that measures the full bounds (left/right/top/bottom) of the text contents:
Rect bounds = new Rect();
CharSequence text = textView.getText();
textView.getPaint().getTextBounds(text, 0, text.length(), bounds);
//bounds now contains the rect of the actual text string
int width = bounds.getWidth();

- 62,780
- 12
- 127
- 139
The Devunwired answer is completely right.
However, it's useful the reader to know that the text width measure in pixels don't need to be linked with any real content of a TextView
or EditText
and isn't restricted to the view widht, so one can simulate if a determinated text fits well in the view before set the view with a text.
Besides, if one uses the whole string you don't need to specify a initial index and a final index (exclusive).
So one can write
float width = textView.getPaint().measureText("my favorite fruit is a banana");
It works smoothly

- 2,471
- 26
- 29
There is no API for this.first you have to find the text size and find lenth of string.finally multipl both you will get width of text in textview.