在用恒定尺寸测量aView后,view.measure()getMeasuredHeight()返回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());

}

最佳答案

当您在view.getMeasuredWidth()onCreate()中调用onCreateView()时,view尚未绘制。所以您需要添加一个监听器,并在绘制view时获得一个回调。就像我的代码中这样:

final ViewTreeObserver vto = view.getViewTreeObserver();
if (vto.isAlive()) {
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int viewWidth = view.getMeasuredWidth();
            // handle viewWidth here...

            if (Build.VERSION.SDK_INT < 16) {
                vto.removeGlobalOnLayoutListener(this);
            } else {
                vto.removeOnGlobalLayoutListener(this);
            }
        }
    });
}

注意:删除侦听器以获得更好的性能!
不要调用vto.removeOnGlobalLayoutListener(this)来删除侦听器。这样称呼:
vto.getViewTreeObserver()

07-26 03:06