gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:45:47 28 4
gpt4 key购买 nike

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

layout_view.xml,扩展以创建 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 height : " + view.getMeasuredHeight());

}

最佳答案

当您在 onCreate()onCreateView() 中调用 view.getMeasuredWidth() 时, 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()

关于android - getmeasuredheight() 和 getmeasuredwidth() 在 View.measure() 之后返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24430429/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com