android – getmeasuredheight()和getmeasuredwidth()在View.measure()之后返回0)

前端之家收集整理的这篇文章主要介绍了android – getmeasuredheight()和getmeasuredwidth()在View.measure()之后返回0)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在使用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);
                    }
            });

注意:删除侦听器以获得更好的性能;

不要调用vto来删除,调用如下:

v.getViewTreeObserver()
原文链接:https://www.f2er.com/android/309816.html

猜你在找的Android相关文章