Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the Text Area(Height/Width) of TextView programmatically in android

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 ?

like image 985
BST Kaal Avatar asked Jun 23 '14 06:06

BST Kaal


4 Answers

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();
like image 105
pigeongram Avatar answered Oct 22 '22 02:10

pigeongram


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.

like image 24
Iosif Avatar answered Oct 22 '22 03:10

Iosif


TextView txt = new TextView(mContext);
txt.setText("Some Text)";
int height = txt.getLineCount() *  txt.getLineHeight();
int width = txt.getWidth();
like image 36
Monir Khlaf Avatar answered Oct 22 '22 02:10

Monir Khlaf


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();

   }
});
like image 34
Haresh Chhelana Avatar answered Oct 22 '22 03:10

Haresh Chhelana