2012-05-11 54 views
0

我需要獲取屏幕尺寸才能使我的應用程序正常工作。要做到這一點,我在我的主要活動中創建了2個函數,並且我通過非Activity類中的對象調用它們。Android從非活動類別獲取圖像大小

出於某種原因,它不斷崩潰。爲什麼我不能調用這些函數?我如何解決它?

代碼主要活動:

public int getWidth(){ 
    Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
    int width = display.getWidth(); 
    return width; 
} 

public int getHeight(){ 
    Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
    int height = display.getHeight(); 
    return height; 
} 

非活動的代碼(主叫方):

main Main = new main(); 
private int height = Main.getHeight(); 
private int width = Main.getWidth(); 

請注意我所知這些方法現在已經過時,但我不能使用的getSize (點);方法,因爲我正在開發最低API級別7.

+0

將您的堆棧跟蹤從y我們的崩潰。 – kabuko

+0

沒有顯示,它在getHeight()的第一行崩潰;因爲這是第一個被調用的函數。 – arielschon12

+0

我們不能在非Activity類的構造函數中傳遞上下文嗎? –

回答

1

你不能只是用它的構造函數創建一個Activity,並期望它被正確初始化。這不是它的工作原理。如果您只是使用構造函數進行調用,則不會獲得獲取系統服務所需的上下文。您需要從活動的實際實例獲取此信息,然後將其傳遞給需要此數據的對象。如果沒有更多的信息/代碼,那麼提供更多細節並不實際。

3

可以創建你在你的ActivityonCreate初始化類Constants包含靜態字段:

public class Constants 
{ 
    public static int DEVICE_WIDTH; 
    public static int DEVICE_HEIGHT; 
} 

活動

onCreate(...) 
{ 
    ... 
    Constants.DEVICE_WIDTH = this.getWidth(); 
    Constants.DEVICE_HEIGHT = this.getHeight(); 
} 

而當你需要這些值,以調用它:

int deviceWidth = Constants.DEVICE_WIDTH;