简体   繁体   English

Android:如何调用get方法显示高度和宽度?

[英]Android: how to call get method to display height and width?

I have been trying to figure out how to find the height and width of the screen in android. 我一直在试图找出如何在android中查找屏幕的高度和宽度。 i have found a way to get it but I dont know how to call the getScreenWidth and getScreenHeight to put values into my int height and int width? 我已经找到一种方法来获取它,但是我不知道如何调用getScreenWidth和getScreenHeight将值放入我的int高度和int宽度?

public class Player {

public int across;
public int upDown;

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;
}

public Player() {

    int width = dmetrics.widthPixels;
    int height = dmetrics.heightPixels;
    int rectSide = 1000;

    //across = startPosX;
    //upDown = startPosY;

}

i am trying to get it by using int width = dmetric.widthPixels; 我试图通过使用int width = dmetric.widthPixels来获取它; but this obviously isnt the way to call the getScreenWidth. 但这显然不是调用getScreenWidth的方法。 Im pretty bad at this stuff, so any help would be great. 我对这些东西很不好,所以任何帮助都会很棒。

You can refer to Here or Here for your answer. 您可以参考此处此处获得答案。 Ps - sorry , I can't comment as I am a beginner so I wrote the answer which should rather be a comment. 附言:对不起,我是初学者,所以无法发表评论,所以我写了答案,应该是评论。

I know, really what im asking is how do i call this get method i have created to set values for width and height? 我知道,实际上我问的是我如何调用这个我创建的用于设置宽度和高度值的get方法? – Phill –菲尔

If you are in an Activity when you wish to call these static methods you could call them this way: 如果您在Activity希望调用这些静态方法,则可以通过以下方式调用它们:

int width = Player.getScreenWidth(this);
int height = Player.getScreenHeight(this);

If you're not in an activity you'll need to know one and pass it instead of this . 如果您在活动是不是你需要知道的一个,并通过它,而不是this

Also be aware that, because of the cast, if you pass something that is a Context but not an Activity it won't work and you won't know it until run time. 另请注意,由于强制转换,如果传递的是Context而不是Activity则它将无法正常工作,并且直到运行时您才知道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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