简体   繁体   中英

How to find the height and width of screen in android

I have a class called crate where i would like to find the height and width. to do this I am using:

public class Crate {
    public int acrossCrate;
    public int upDownCrate;

    public Crate(Context context) {

    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    int width = metrics.widthPixels;
    int height = metrics.heightPixels;
}
}

But I have another class called draw which calls the crate class, and when i use the Context context in crate it gives an error when calling it in the draw class:

public class Draw extends View {
    float x, y;
    Paint red = new Paint();
    Paint green = new Paint();
    Paint black = new Paint();
    Paint blue = new Paint();
    Bitmap player;
    Bitmap crate;
    int rectSide = 1000;

    Player thePlayer = new Player();
    Crate theCrate = new Crate();//<-- ERROR when i use Context context

Im really stuck and if anyone knows how to do this and could help me that would be great.

Call like this

 Crate theCrate;

and in constructor

theCrate = new Crate(context);

Once try the following methods

// Get screen width
public static int getScreenWidth(Context c) {
    DisplayMetrics dmetrics = new DisplayMetrics();
    ((Activity) c).getWindowManager().getDefaultDisplay()
            .getMetrics(dmetrics);
    return dmetrics.widthPixels;
}

// Get screen height
public static int getScreenHeight(Context c) {
    DisplayMetrics dmetrics = new DisplayMetrics();
    ((Activity) c).getWindowManager().getDefaultDisplay()
            .getMetrics(dmetrics);
    return dmetrics.heightPixels;
}

Hope this will helps you.

Its easy...if Your View class is the Size of the full screen just use the getWidth() and getHeight() methods of this class

Otherwise get it from the windowmanager methods like other suggested

if (Build.VERSION.SDK_INT >= 11) {
    Point size = new Point();
    try {
        this.getWindowManager().getDefaultDisplay().getRealSize(size);
        screenWidth = size.x;
        screenHeight = size.y;
    } catch (NoSuchMethodError e) {
         screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
         screenWidth=this.getWindowManager().getDefaultDisplay().getWidth();
    }

} else {
    DisplayMetrics metrics = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
    screenWidth = metrics.widthPixels;
    screenHeight = metrics.heightPixels;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM