Java 视图的高度和宽度始终为0(getMeasuredHeight()和getHeight()都不工作)
我在Java 视图的高度和宽度始终为0(getMeasuredHeight()和getHeight()都不工作),java,android,android-layout,android-linearlayout,Java,Android,Android Layout,Android Linearlayout,我在LinearLayout内部有一个LinearLayout,子LinearLayout有其布局参数,其中高度和宽度定义为 LinearLayout linearLayout=new LinearLayout(context); LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(50,50); linearLayout.setLayoutParams(lp); 现在,在创建视图之后,我正在尝试
LinearLayout
内部有一个LinearLayout
,子LinearLayout
有其布局参数
,其中高度和宽度定义为
LinearLayout linearLayout=new LinearLayout(context);
LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(50,50);
linearLayout.setLayoutParams(lp);
现在,在创建视图之后,我正在尝试从getHeight()
和getmeasuredheath()
获取视图的高度,但这两种方法都返回0
int heightofView=linearLayout.getHeight();
int heightofview=linearLayout.getMeasuredHeight();
为什么这两种方法都返回视图的0高度?这些方法何时返回实际结果?如何获取我创建的视图的高度?试试下面的代码
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);
}
});
试试这个代码
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);
}
});
按以下步骤做-
linearLayout.post(new Runnable() {
@Override
public void run() {
int linearLayoutHeight = linearLayout.getHeight();
Log.e("MS", "linearLayout Ht = " + linearLayoutHeight);
}
});
按以下步骤做-
linearLayout.post(new Runnable() {
@Override
public void run() {
int linearLayoutHeight = linearLayout.getHeight();
Log.e("MS", "linearLayout Ht = " + linearLayoutHeight);
}
});