2011-11-20 73 views

回答

37
Display display = getWindowManager().getDefaultDisplay(); 
View view = findViewById(R.id.YOUR_VIEW_ID); 
view.measure(display.getWidth(), display.getHeight()); 

view.getMeasuredWidth(); // view width 
view.getMeasuredHeight(); //view height 
+0

请标记为已解决^^ –

+4

您可能还要记住,如果视图没有被充气,它的宽度和高度将会是0. – Joru

+0

您是对的Joru。我使用ViewTreeObserver并解决了我的问题。感谢所有试图回答的人。 –

23

@dmytrodanylyk - 我认为它会返回宽度&高度为0,所以你需要使用下面的事情

LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View contentview = inflater.inflate(R.layout.YOURLAYOUTNAME, null, false); 
contentview.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); 
int width = contentview.getMeasuredWidth(); 
int height = contentview.getMeasuredHeight(); 

它会给你正确的高度&宽度。

+0

这就是我需要确定是否应该开始一个新的复选框,首先使它成为一个单一的行,然后通过计算宽度来防止溢出...完美谢谢。来自 - > http://stackoverflow.com/a/24054428/1815624 – CrandellWS

9

您应该使用OnGlobalLayoutListener,它被视为在视图上进行了更改,但在绘制之前进行了更改。

costumView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 

    @Override 
    public void onGlobalLayout() { 

     costumView.getWidth(); 

    } 
}); 
2

我喜欢使用这种技术,因为每my answer on a related question

邮政从onCreate()可运行视图已经被创建时将被执行:

contentView = findViewById(android.R.id.content); 
    contentView.post(new Runnable() 
    { 
     public void run() 
     { 
      contentHeight = contentView.getHeight(); 
     } 
    }); 

该代码将在运行主要UI线程,在onCreate()完成后。

0

这是最好的方法......工作!

public void onWindowFocusChanged(boolean hasFocus) {   
    super.onWindowFocusChanged(hasFocus); 

    if (fondo_iconos_height==0) { // to ensure that this does not happen more than once 
     fondo_iconos.getLocationOnScreen(loc); 
     fondo_iconos_height = fondo_iconos.getHeight(); 
     redraw_function(); 
    } 

} 
5
Display display = getWindowManager().getDefaultDisplay(); 
Point size = new Point(); 
display.getSize(size); 
view.measure(size.x, size.y); 
int width = view.getMeasuredWidth(); 
int height = view.getMeasuredHeight(); 
0
yourView.measure(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
    int yourView= m_hidableRowContainer.getMeasuredHeight(); 

就是这样。

+0

'measure'需要一对'View.MeasureSpec'整型常量,而不是布局参数常量。 – Tom

相关问题