在非活动扩展类(Android)中获取屏幕维度
出于某种原因,我必须在非活动扩展类中获取屏幕维度。我尝试使用以下方法:在非活动扩展类(Android)中获取屏幕维度,android,android-activity,screen,dimension,Android,Android Activity,Screen,Dimension,出于某种原因,我必须在非活动扩展类中获取屏幕维度。我尝试使用以下方法: DisplayMetrics metrics = this.getResources().getDisplayMetrics(); int w = metrics.widthPixels; 所以我可以用“w”作为宽度尺寸,以像素为单位。然而,这种方法似乎只适用于扩展活动的类。有解决办法吗 谢谢大家。为了访问活动方法,而无需在每次需要时传递上下文,在应用程序对象中保留对当前活动的引用非常有用- public class Yo
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
int w = metrics.widthPixels;
所以我可以用“w”作为宽度尺寸,以像素为单位。然而,这种方法似乎只适用于扩展活动的类。有解决办法吗
谢谢大家。为了访问
活动
方法,而无需在每次需要时传递上下文
,在应用程序对象中保留对当前活动的引用非常有用-
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>
另外,我通常有一个
ParentActivity
,由我的其他活动扩展,将一些常见的逻辑分组,如此。为了访问活动
方法,而无需每次需要时传递上下文
,在应用程序对象中保留对currentActivity的引用非常有用-
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>
此外,我通常有一个
ParentActivity
,由我的其他活动扩展,将一些常见的逻辑分组,如以下逻辑。您必须在上下文中通过类的构造函数传递:
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;
}
}
必须在上下文中通过类的构造函数传递:
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;
}
}
你试过了吗?你试过了吗?