1

Using android, does anybody know how to get the exact width of a textview, in pixel, before it's displayed on the screen ? (programmatically) I've search a lot on the internet but I didn't found anything working.

Thank you

Links of the post I tried :

    1. With a Paint
      With measure
      With density
  • Community
    • 1
    • 1
    Kemix
    • 25
    • 5

    4 Answers4

    3

    It was better that you had sent some code. Then we could help you more. But I think that you may use these methods:

    yourText.measure(0, 0);
    

    And then these codes:

    int width = view.getMeasuredWidth();
    int height = view.getMeasuredHeight();
    
    • Sorry, I just thought that this way didn't work but in fact my code was bad... Thank you very much for your quick answer – Kemix Jun 20 '16 at 19:39
    3

    I think that you should use OnGlobalLayoutListener which is usually used to find out the height and the width of views before they are drawn.

    For example,

    yourTextView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    
        @Override
        public void onGlobalLayout() {
    
          yourTextView.getWidth();
    
        }
    });
    
    Cache Staheli
    • 3,510
    • 7
    • 32
    • 51
    0

    try this.

    textView.setText("your text");
    textView.measure(0, 0);
    textView.getMeasuredWidth();
    textView.getMeasuredHeight();
    
    Ashish Kudale
    • 1,230
    • 1
    • 27
    • 51
    0

    As Nargess said you'd better use methods of measuring view's width and height, like code below:

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    view.measure(size.x, size.y);
    int width = view.getMeasuredWidth();
    int height = view.getMeasuredHeight();
    
    Hossein Seifi
    • 1,380
    • 11
    • 29