Android从非活动类获取图像大小

时间:2012-05-11 19:25:40

标签: android screen

我需要获取屏幕尺寸才能使我的应用程序正常工作。为此,我在我的主要活动中创建了2个函数,并通过非Activity类中的对象调用它们。

出于某种原因,它一直在崩溃。为什么我不能称这些功能?我该如何解决?

主要活动代码:

    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(point);方法,因为我正在开发最低API级别7.

2 个答案:

答案 0 :(得分:3)

您可以创建一个类Constants,其中包含您在onCreate的{​​{1}}中初始化的静态字段,如:

Activity

活动

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

当您需要这些值时,请将其命名为:

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

答案 1 :(得分:1)

你不能只用它的构造函数创建一个Activity,并期望它被正确初始化。这不是它的工作原理。如果只是使用构造函数调用,它将不具有获取系统服务所需的上下文。您需要从活动的实际实例获取此信息,然后将其传递给需要此数据的对象。没有更多的信息/代码,提供更多细节并不是真的可行。