2012-08-22 116 views
15

如何获取在xml中定义为fill_parent的高度和宽度的线性布局的宽度和高度?我尝试过测量方法,但我不知道它为什么没有给出确切的价值。在oncreate方法完成之前,我需要在Activity中使用这些值。获取运行时的布局高度和宽度android

+0

IIRC在测量之前,您无法获得任何东西的高度/宽度。当onSizeChanged被调用时,它被分配,如果你重载onLayout所有视图应该有一个高度和宽度 – tom502

+0

@ tom502你可以给我一个链接或一段代码?这将是非常有益的。 – MGDroid

回答

31

想我必须得在XML定义的LinearLayout宽度。我必须通过XML获取它的参考。定义LinearLayoutl作为实例。

l = (LinearLayout)findviewbyid(R.id.l1); 
ViewTreeObserver observer = l.getViewTreeObserver(); 
     observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 

      @Override 
      public void onGlobalLayout() { 
       // TODO Auto-generated method stub 
       init(); 
      l.getViewTreeObserver().removeGlobalOnLayoutListener(
        this); 
     } 
    }); 

protected void init() { 
     int a= l.getHeight(); 
      int b = l.getWidth(); 
Toast.makeText(getActivity,""+a+" "+b,3000).show(); 
    } 
    callfragment(); 
} 
+1

注意!在onCreate完成之前它不会给你值。 Alhought我已经在onCreate方法中调用它的覆盖方法将被称为迟了。所以看起来你的应用程序运行缓慢,但它解决了我的目的。 – MGDroid

5

宽度和高度值是在创建布局之后设置的,当元素被放置后,它们被测量。在第一次调用onSizeChanged时,parms将为0,所以如果您使用该检查。

这里更详细一点 https://groups.google.com/forum/?fromgroups=#!topic/android-developers/nNEp6xBnPiw

这里http://developer.android.com/reference/android/view/View.html#Layout

下面是如何使用onLayout:

@Override 
protected void onLayout(boolean changed, int l, int t, int r, int b) { 
    int width = someView.getWidth(); 
    int height = someView.getHeight(); 
} 
2

你可以在配置变更监听器添加到您的布局,获得最新的高度和宽度,甚至最后改变之前的一个。

在API级别11

添加监听将被调用时,视图变化 的边界由于布局处理。

LinearLayout myLinearLayout = (LinearLayout) findViewById(R.id.my_linear_layout); 
myLinearLayout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { 
     @Override 
     public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { 
      // Preventing extra work because method will be called many times. 
      if(height == (bottom - top)) 
       return; 

      height = (bottom - top); 
      // do something here... 
      } 
    }); 
3

得到它的工作,你需要检查所需的高度值是否大于0 - 和第一然后取出onGlobalLayout听众,做任何你想要的高度。监听者不断地调用它的方法,并且在第一次调用时不能保证视图被正确测量。

final LinearLayout parent = (LinearLayout) findViewById(R.id.parentView); 
    parent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
      int availableHeight = parent.getMeasuredHeight(); 
      if(availableHeight>0) { 
       parent.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
       //save height here and do whatever you want with it 
      } 
     } 
    }); 
+0

这样做 - 谢谢。删除监听器调用已从API级别16弃用。本文描述如何支持早期和后期API的调用http://stackoverflow.com/a/23741481/2162226 – gnB

相关问题