gpt4 book ai didi

android - measureSpec 返回错误值

转载 作者:行者123 更新时间:2023-11-30 02:22:03 25 4
gpt4 key购买 nike

我正在尝试使用以下代码测量布局的高度:

int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(toExpand.getWidth(), View.MeasureSpec.EXACTLY);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
layoutHeight.measure(widthMeasureSpec, heightMeasureSpec);
int height = layoutHeight.getMeasuredHeight();

如果我在创建布局后调用它,它会返回良好的值,但我也在应用程序启动时调用它,当 fragment 被附加时,它返回比预期高得多的值。

有什么想法吗?感谢转发

最佳答案

通过将 onGlobalLayout 监听器与 viewTreeObserver 一起使用解决了这个问题。这是代码:

ViewTreeObserver vto = ((View) loadingLayout.getParent()).getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ViewTreeObserver vto = ((View) loadingLayout.getParent()).getViewTreeObserver();
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(toExpand.getWidth(), View.MeasureSpec.EXACTLY);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
layoutHeight.measure(widthMeasureSpec, heightMeasureSpec);
int height = layoutHeight.getMeasuredHeight();
if(toExpand.getHeight() == height){
hide(toExpand, 0);
}else{
expand(toExpand, height);
}
if (Build.VERSION.SDK_INT < 16) {
//deprecated od API level 16
vto.removeGlobalOnLayoutListener(this);
} else {
vto.removeOnGlobalLayoutListener(this);
}
}
});

关于android - measureSpec 返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28340432/

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