gpt4 book ai didi

java - View 的高度和宽度始终为 0(getMeasuredHeight() 和 getHeight() 均无效)

转载 作者:行者123 更新时间:2023-11-29 06:30:35 25 4
gpt4 key购买 nike

我在 LinearLayout 中有一个 LinearLayout 并且子 linearlayout 有它的 layout params 其中 height width 定义为

LinearLayout linearLayout=new LinearLayout(context);
LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(50,50);
linearLayout.setLayoutParams(lp);

现在创建 View 后,我试图从 getHeight()getMeasuredHeight() 获取 View 的高度,但两种方法都返回 0 . ?

  int heightofView=linearLayout.getHeight(); 
int heightofview=linearLayout.getMeasuredHeight();

为什么这两种方法都返回 0 高度的 View ?这些方法何时返回实际结果?如何获取我创建的 View 的高度?

最佳答案

试试这段代码。

imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int width = imageView.getWidth();
int height = imageView.getHeight();
//you can add your code here on what you want to do to the height and width you can pass it as parameter or make width and height a global variable
imageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});

关于java - View 的高度和宽度始终为 0(getMeasuredHeight() 和 getHeight() 均无效),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35310386/

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