我试图通过使用以下代码来获得测量的布局高度:
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();
如果我在创建布局后调用它,它会返回好的值,但是当片段被连接时我也在应用程序启动时调用它,然后它返回的值比预期值高得多。
有什么想法吗?谢谢你前进
答案 0 :(得分:1)
通过使用带有viewTreeObserver的onGlobalLayout侦听器解决了这个问题。这是代码:
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);
}
}
});