Ciaran
Ciaran

Reputation: 695

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.

Upvotes: 0

Views: 101

Answers (3)

Ilja KO
Ilja KO

Reputation: 1616

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

Upvotes: 0

Nagaraju V
Nagaraju V

Reputation: 2757

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.

Upvotes: 2

Chandrakanth
Chandrakanth

Reputation: 3831

Call like this

 Crate theCrate;

and in constructor

theCrate = new Crate(context);

Upvotes: 2

Related Questions