2011-11-20 46 views

Trả lời

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

Vui lòng đánh dấu là đã giải quyết ^^ –

+4

Bạn cũng có thể nhớ rằng nếu chế độ xem không bị thổi phồng, chiều rộng và chiều cao sẽ là 0. – Joru

+0

Bạn đúng Joru. Tôi đã sử dụng ViewTreeObserver và giải quyết vấn đề của mình. Cảm ơn tất cả những ai đã cố gắng trả lời. –

23

@dmytrodanylyk - Tôi nghĩ rằng nó sẽ trở về chiều rộng & chiều cao là 0, do đó bạn cần phải sử dụng sau điều

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(); 

Nó sẽ cho bạn chiều cao đúng & chiều rộng.

+0

Đó là những gì tôi cần xác định xem tôi có nên bắt đầu một hàng mới của hộp kiểm hay không, trước tiên hãy tạo một hộp kiểm dòng và sau đó ngăn chặn tràn bằng cách tính toán chiều rộng ... hoàn hảo cảm ơn bạn. đến từ -> http://stackoverflow.com/a/24054428/1815624 – CrandellWS

9

Bạn nên sử dụng OnGlobalLayoutListener được gọi cho các thay đổi trên chế độ xem, nhưng trước khi được vẽ.

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

    @Override 
    public void onGlobalLayout() { 

     costumView.getWidth(); 

    } 
}); 
2

Tôi thích sử dụng kỹ thuật này theo my answer on a related question:

Đăng một Runnable từ onCreate() đó sẽ được thực hiện khi xem đã được tạo:

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

Mã này sẽ chạy trên chủ đề giao diện người dùng chính, sau khi onCreate() kết thúc.

0

Đây là cách tốt nhất ...... LÀM VIỆC !!!

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(); 

Vậy là xong.

+0

'measure' lấy một cặp' hằng số View.MeasureSpec', không phải là hằng số param bố cục. – Tom

Các vấn đề liên quan