I have an EditText
, a Button
and a TextView
. On clicking the button, textview shows the text written in edittext. Is it possible to find the size of textview occupied depending upon text. i.e. If It has three characters "abc", what is width now, if it has 5 characters like "abcde" , then what is the width ?
Asked
Active
Viewed 3.0k times
25
5 Answers
80
Rect bounds = new Rect();
Paint textPaint = textView.getPaint();
textPaint.getTextBounds(text,0,text.length(),bounds);
int height = bounds.height();
int width = bounds.width();
or
textView.setText("bla");
textView.measure(0, 0);
textView.getMeasuredWidth();
textView.getMeasuredHeight();

pigeongram
- 918
- 7
- 4
-
1This works quite nicely - until the text is too long to fit into one line and wraps, adding a second line. Since getTextBounds() does not know about the space available for a line of text, the calculated height will be severely underestimating the actual height. – xmjx Jun 26 '21 at 13:12
11
Please try this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView edit = (TextView) findViewById(R.id.edit);
edit.setTextSize(20);
edit.setText("Hello, world");
edit.measure(0, 0);
int width = edit.getMeasuredWidth();
Log.w("width", width.toString());
}
Before you get width, you have to measure the view / label / text edit. Please let me know if this is not working.
-
Both of the answers are correct , yours and the above one...Thnx its working. – BST Kaal Jun 23 '14 at 06:48
-
Plese mark as answer (the button below down-vote) And i'm glad it worked. – Iosif Jun 23 '14 at 06:49
-
This will return 0 because the view has not been drawn yet. It has to be done in a Runnable in `view.post()` for you to get the dimensions – OzzyTheGiant Aug 23 '19 at 16:07
7
TextView txt = new TextView(mContext);
txt.setText("Some Text)";
int height = txt.getLineCount() * txt.getLineHeight();
int width = txt.getWidth();

Monir Khlaf
- 567
- 7
- 5
3
Try this way,hope this will help you to solve your problem.
yourTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int width = yourTextView.getMeasuredWidth();
int height = yourTextView.getMeasuredHeight();
}
});

M D
- 47,665
- 9
- 93
- 114

Haresh Chhelana
- 24,720
- 5
- 57
- 67
-
Hello @M D, can u plz take a look at http://stackoverflow.com/questions/25196894/how-to-get-list-item-data-in-bindview-when-clicking-on-radiobutton-in-android – BST Kaal Aug 08 '14 at 14:21
2
please tell me width in??? do you want ?
TextView
method getWidth()
gives you width of your view, in pixels
TextView textView = (TextView)findViewById(R.id.textview);
textView.getWidth(); //width of your view, in pixels

MilapTank
- 9,988
- 7
- 38
- 53