gpt4 book ai didi

java - 全局布局监听器返回 0

转载 作者:行者123 更新时间:2023-12-01 18:35:15 24 4
gpt4 key购买 nike

您好,我想通过全局布局监听器获取相对布局的高度和宽度:

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);
}
}
});

关于java - 全局布局监听器返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60072544/

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