The answer to this question may be too advanced for me, but I would still like to give it a try. I am able to determine and set the value for the screen size within a method, but it does not have scope outside of that method. My question is, how do I give it scope inside the entire class? Also inside the entire project? Thanks. Here is what I am using to determine the screen size, but it only works inside a single method:
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
Thanks!
My question is, how do I give it scope inside the entire class? Also inside the entire project?
If you only want to worry about setting those values once, extending the Application
class would probably be a good start.
public class MyApplication extends Application {
private Point mDimensions;
@Override public void onCreate() {
// this will only get run on app startup
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
mDimensions = new Point(width, height);
}
public int getWidth() {
return mDimensions.x;
}
public int getHeight() {
return mDimensions.y;
}
}
To access the getter methods, set the android:name
attribute on the application tag in your project's manifest:
<application android:name="com.myname.MyApplication" ... ></application>
You can then cast the result of any getApplication()
and getApplicationContext()
call to MyApplication
and call the methods; e.g.
int width = ((MyApplication) getApplication()).getWidth();
Do note that since the width and height values are initialized only once, they will not change on screen orientation changes. If you want to take that into account too, a simple util method accepting a context instance (can be e.g. an Activity
or Service
) is probably a more straightforward solution.
public static Point getDimensions(Context context) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
return new Point(width, height);
}