在View.measure()之后,getmeasuredheight()和getmeasuredwidth()返回0. [英] getmeasuredheight() and getmeasuredwidth() returns 0 after View.measure()

查看:323
本文介绍了在View.measure()之后,getmeasuredheight()和getmeasuredwidth()返回0.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用view.measure()测量具有恒定尺寸View之后,getMeasuredHeight()getMeasureWidth()返回0.

After measuring a View with a constant dimensions with view.measure(), the getMeasuredHeight() and getMeasureWidth() is returning 0.

layout_view.xml ,被夸大以创建视图的布局

layout_view.xml, layout which is inflated to create the view

<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()时,尚未绘制view.因此,您需要添加一个侦听器,并在绘制view时获得回调.就像我的代码中这样:

When you call view.getMeasuredWidth() in onCreate() or onCreateView(), the view has not been drawn yet. So you need to add a listener and will get a callback when the view is being drawn. Just like this in my code:

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);
            }
        }
    });
}

注意::删除监听器以获得更好的性能!

NOTE: Remove the listener for better performance!

请勿调用vto.removeOnGlobalLayoutListener(this)删除监听器.这样称呼它:

Don't call vto.removeOnGlobalLayoutListener(this) to remove the listener. Call it like this:

vto.getViewTreeObserver()

这篇关于在View.measure()之后,getmeasuredheight()和getmeasuredwidth()返回0.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆