how to get width in pixels of view with android:layout_width="wrap_content"?
Asked Answered
T

4

5

I have view, which have layout_width="wrap_content". If i use view.getWidth() in code, it returns 0. :-( How can I convert width of view "wrap_content" to pixels?

Tantalic answered 19/8, 2010 at 9:17 Comment(0)
P
5

You could try getMeasuredWidth instead. but if it returns 0, that means the View is not ready when you try to measure it. try to make the call later. Like in a thread you poste when onCreate is finished

Pickmeup answered 19/8, 2010 at 10:27 Comment(0)
C
3

it depends when are you calling view.getWidth() .The result will always be 0 if the view is not visible [onCreate , onResume] .

Try to call view.getWidth in

 @Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    // call get width here

}

Hope this will help .

Coffeng answered 23/10, 2014 at 13:10 Comment(0)
L
1
Button b = (Button) yourView.findViewById(R.id.your_button_id);
System.out.println("b.getMeasuredHeight() = "+b.getMeasuredHeight());
System.out.println("b.getMeasuredWidth() + "+ b.getMeasuredWidth());
Lamia answered 11/12, 2014 at 20:26 Comment(0)
G
0
  • call view.getWidth in view.post()
  • call view.getWidth in view.getViewTreeObserver().addGlobalLayoutListener()

Remember do not call view.getWidth() directly in onCreate(), cause the measuring process is not performed yet, where you can only get 0 returned by getWidth().

Godunov answered 2/7, 2021 at 5:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.