Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 607
Andrei Avatar asked Aug 19 '10 09:08

Andrei


3 Answers

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

like image 191
Sephy Avatar answered Oct 03 '22 23:10

Sephy


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 .

like image 27
M.Khouli Avatar answered Oct 04 '22 01:10

M.Khouli


Button b = (Button) yourView.findViewById(R.id.your_button_id);
System.out.println("b.getMeasuredHeight() = "+b.getMeasuredHeight());
System.out.println("b.getMeasuredWidth() + "+ b.getMeasuredWidth());
like image 44
Gene Avatar answered Oct 03 '22 23:10

Gene