Android measureSpec返回错误的值
我试图通过使用以下代码获得布局的测量高度:Android measureSpec返回错误的值,android,android-layout,Android,Android Layout,我试图通过使用以下代码获得布局的测量高度: int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(toExpand.getWidth(), View.MeasureSpec.EXACTLY); int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); layoutHeight.meas
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();
若我在创建布局后调用它,它会返回很好的值,但在应用程序启动时,当片段被附加时,我也会调用它,然后它会返回比预期高得多的值
有什么想法吗?感谢转发通过使用onGlobalLayout listener和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);
}
}
});
ViewTreeObserver vto=((视图)loadingLayout.getParent()).getViewTreeObserver();
vto.addOnGlobalLayoutListener(新的ViewTreeObserver.OnGlobalLayoutListener(){
@凌驾
公共图书馆{
ViewTreeObserver vto=((视图)loadingLayout.getParent()).getViewTreeObserver();
int-widthmasurespec=View.MeasureSpec.makeMeasureSpec(toExpand.getWidth(),View.MeasureSpec.justice);
int heightMeasureSpec=View.MeasureSpec.MakeMasureSpec(0,View.MeasureSpec.UNSPECIFIED);
布局尺寸(宽度尺寸、高度尺寸);
int height=layouthweight.getMeasuredHeight();
if(toExpand.getHeight()==高度){
隐藏(toExpand,0);
}否则{
扩展(扩展范围、高度);
}
如果(Build.VERSION.SDK_INT<16){
//不推荐的od API级别16
vto.移除LobalonlayOutliner(本);
}否则{
vto.removeOnGlobalLayoutListener(此);
}
}
});
你有没有弄明白为什么度量值在onGlobalLayout()之外不起作用?