我在LinearLayout
内有LinearLayout
而子linearlayout
有layout params
,height
和width
定义为
LinearLayout linearLayout=new LinearLayout(context);
LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(50,50);
linearLayout.setLayoutParams(lp);
现在,在创建视图后,我尝试从getHeight()
和getMeasuredHeight()
获取视图的高度,但这两种方法都返回 0 。 ?
int heightofView=linearLayout.getHeight();
int heightofview=linearLayout.getMeasuredHeight();
为什么这两个方法都返回0视图的高度?当这些方法返回实际结果时?如何获得我创建的视图的高度?
答案 0 :(得分:5)
试试这段代码。
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);
}
});
答案 1 :(得分:2)
执行以下操作 -
linearLayout.post(new Runnable() {
@Override
public void run() {
int linearLayoutHeight = linearLayout.getHeight();
Log.e("MS", "linearLayout Ht = " + linearLayoutHeight);
}
});