我有一个视图,它的layout_width属性为“wrap_content”。如果我在代码中使用view.getWidth(),它会返回0。:-( 如何将视图“wrap_content”的宽度转换为像素?
getMeasuredWidth
代替,但如果返回0,则意味着在尝试测量View时它还没有准备好。请稍后再次调用。比如在onCreate完成后的线程中。视情况而定,当您调用view.getWidth()时,结果将取决于何时进行调用。如果视图不可见[在onCreate、onResume阶段],则结果始终为0。
请尝试在
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
// call get width here
}
Button b = (Button) yourView.findViewById(R.id.your_button_id);
System.out.println("b.getMeasuredHeight() = "+b.getMeasuredHeight());
System.out.println("b.getMeasuredWidth() + "+ b.getMeasuredWidth());
记得不要直接在onCreate()中调用view.getWidth(),因为此时还没有进行测量过程,getWidth()方法只会返回0。