How to get width in pixels of view using android: layout_width = "wrap_content"?

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

+4
source share
3 answers

Instead, you can try getMeasuredWidth . but if it returns 0, it means the view is not ready when you try to measure it. try calling later. How in the stream do you post when onCreate is complete

+4
source

It depends on when you call view.getWidth (). The result will always be 0 if the view is not displayed [onCreate, onResume].

Try calling view.getWidth in

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

Hope this helps.

+3
source
 Button b = (Button) yourView.findViewById(R.id.your_button_id); System.out.println("b.getMeasuredHeight() = "+b.getMeasuredHeight()); System.out.println("b.getMeasuredWidth() + "+ b.getMeasuredWidth()); 
0
source

All Articles