2012-10-10 184 views
3

我使用下面的步驟來知道我的顯示屏內容視圖的寬度和高度

ContentViewWidth = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getWidth(); 
ContentViewHeight = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getHeight(); 

的內容查看的寬度和高度,但這種方法並不裏面的onCreate或工作的onResume,如果我使用這些步驟在onWindowFocusChanged裏面我的手機上出現強制關閉錯誤

請幫我看看我的顯示屏幕的內容視圖。內容視圖不包括狀態欄和標題欄維度

+0

您可能需要在創建它 – sherpya

+0

中的onDraw嘗試之前,使用http://developer.android.com/reference/android/util/DisplayMetrics.html你不能有客戶區() – muratonnet

回答

0

下面是我在我的活動中所做的工作,以確定我認識的特定視圖子視圖的內容佈局(本例中爲webview):

首先,從OnGlobalLayoutListener繼承:

public class ContainerActivity extends Activity implements ViewTreeObserver.OnGlobalLayoutListener { 
... 

接下來,實施onGlobalLayout監聽器的接口的方法(注意我做的,涉及到找出中等變焦蘸些像素Calcs(計算):

@Override 
public void onGlobalLayout() { 
    int nH = this.mWebView.getHeight(); 
    int nW = this.mWebView.getWidth(); 

    if (nH > 0 && nW > 0) 
    { 
     DisplayMetrics oMetrics = new DisplayMetrics(); 

     this.getWindowManager().getDefaultDisplay().getMetrics(oMetrics); 

     nH = (nH * DisplayMetrics.DENSITY_DEFAULT)/oMetrics.densityDpi; 
     nW = (nW * DisplayMetrics.DENSITY_DEFAULT)/oMetrics.densityDpi; 

     // do something with nH and nW     

     this.mWebView.getViewTreeObserver().removeGlobalOnLayoutListener 
      (this 
      ); 

      ...   
    } 
} 

最後,確保裏面,您正在收聽的onCreate()視圖元素(mWebView在這種情況下)告訴佈局事件:

this.setContentView(this.mWebView = new WebView(this)); 

this.mWebView.getViewTreeObserver().addOnGlobalLayoutListener 
    (this 
    ); 

這種方法適用於較舊的Android版本。我相信ics +對於每個你可以綁定的視圖都有一個佈局監聽器,因此可以以類似的方式使用它。

1

我用下面的技術 - 從onCreate()發佈可運行的觀點已經被創建時將被執行:

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

此代碼將在主UI線程上運行,onCreate()結束後。


如果你想獲取內容視圖本身的高度,你需要減去從高度填充 - 這是由於Android 2.x的不同勾畫出的意見,4.x的

contentHeight = contentView.getHeight() - contentView.getTopPadding(); 
0
Rect rectangle = new Rect(); 
Window window = getWindow(); 
window.getDecorView().getWindowVisibleDisplayFrame(rectangle); 
int contentHeight = window.findViewById(Window.ID_ANDROID_CONTENT).getHeight(); 
int contentWidth = window.findViewById(Window.ID_ANDROID_CONTENT).getWidth(); 
相關問題