视图的高度和宽度始终为0(getMeasuredHeight()和getHeight()都不起作用)

时间:2016-02-10 08:45:51

标签: java android android-layout android-linearlayout

我在LinearLayout内有LinearLayout而子linearlayoutlayout paramsheightwidth定义为

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视图的高度?当这些方法返回实际结果时?如何获得我创建的视图的高度?

2 个答案:

答案 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);
            }
        });
相关问题