全局布局侦听器返回 0



您好,我想使用全局布局侦听器获取相对布局的高度和宽度:

final RelativeLayout relativeLayout = binding.rl;
relativeLayout.getViewTreeObserver()
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
width = relativeLayout.getWidth();
height = relativeLayout.getHeight();
relativeLayout.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
}
});

我的代码问题是宽度和高度为零。有人可以告诉我任何解决方案吗?提前谢谢。

<RelativeLayout
android:id="@+id/rl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/dp12">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>

如果您没有其他选择,请尝试使用 getMeasuredWidth(( 或 getMeasuredHeight(( :

relativeLayout.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
int width = relativeLayout.getMeasuredWidth();
int height = relativeLayout.getMeasuredHeight();

但是根据您的问题,仅当高度或权重高于 0 时才尝试删除 OnGlobalLayoutListener,因为如果您的布局宽度/高度为"wrap_content",则实际上可能是 0 :

relativeLayout.getViewTreeObserver()
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
width = relativeLayout.getWidth();
height = relativeLayout.getHeight();
if (width > 0) {
relativeLayout.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
}
}
});

最新更新