2013-09-28 42 views
1

由于某些原因,我必须获取非活动扩展类中的屏幕尺寸。我试着用下面的方法:在非活动扩展类(Android)中获取屏幕尺寸

DisplayMetrics metrics = this.getResources().getDisplayMetrics(); 
int w = metrics.widthPixels; 

所以我可以使用“w”作为宽度尺寸的像素。但是,这种方法似乎只适用于扩展活动的类。任何解决方案

谢谢大家。

+0

你尝试http://stackoverflow.com/a/1016941/1023092? – Joe

回答

0

为了访问Activity方法,而无需每次你需要它的时候通过context,它保持到currentActivity参考您的应用程序object.-

public class YourApplication extends Application { 
    public YourApplication() { 
     instance = this;   
    } 

    public static YourApplication getInstance() { 
     return instance; 
    } 

    public Activity getCurrentActivity() { 
     return currentActivity; 
    } 

    public void setCurrentActivity(Activity currentActivity) { 
     this.currentActivity = currentActivity; 
    } 
} 

在你AndroidManifest.xml

是非常有用的
<application 
    android:name=".YourApplication" 
    ... 
    > 
</application> 

而在你ActivitiesonResume method.-

@Override 
protected void onResume() { 
    super.onResume(); 

    YourApplication.getInstance().setCurrentActivity(this); 
} 

另外,我通常有一个ParentActivity被我的其余活动延伸,将这些共同的逻辑分组。

1

你必须通过类的构造函数中的上下文来传递:

public class Something { 

    Context context; 

    public Something(Context context){ 
     this.context = context; 
    } 

    public int getDisplayWidth(){ 
     DisplayMetrics metrics = this.context.getResources().getDisplayMetrics(); 
     int w = metrics.widthPixels; 
     return w; 
    } 
}