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?
how to get width in pixels of view with android:layout_width="wrap_content"?
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
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 .
Button b = (Button) yourView.findViewById(R.id.your_button_id);
System.out.println("b.getMeasuredHeight() = "+b.getMeasuredHeight());
System.out.println("b.getMeasuredWidth() + "+ b.getMeasuredWidth());
- 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().
© 2022 - 2024 — McMap. All rights reserved.