在使用view.measure()测量具有恒定维度的视图后,getMeasuredHeight()和getMeasureWidth()返回0.
layout_view.xml,用于创建视图的布局
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="100dp" android:layout_height="100dp"> </FrameLayout>
测量尺寸的功能
public void measureView(Context context){ LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.layout_view,null,false); view.measure( View.MeasureSpec.UNSPECIFIED,View.MeasureSpec.UNSPECIFIED); Log.d(TAG,"Error width : " + view.getMeasuredWidth()); Log.d(TAG,"Error heeght : " + view.getMeasuredHeight()); }
解决方法
当您调用onCreate()或onCreateView()中的view.getMeasuredWidth()时,该视图尚未绘制.所以,您需要添加一个listen,并在绘制视图时获取回调.就像我的代码一样:
ViewTreeObserver vto = view.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { int viewWidth = view.getMeasuredWidth(); // handle viewWidth here... if (Build.VERSION.SDK_INT<16) { v.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { v.getViewTreeObserver().removeOnGlobalLayoutListener(this); } });
v.getViewTreeObserver()