安卓:如何找到屏幕的宽度和高度?

5

我正在尝试查找屏幕的宽度和高度,但是我创建的类中没有一种方法有效。我的代码如下。

有人知道如何找到它吗?我不能使用我下面尝试的方式,因为.getWidth()已经被弃用了。

public class Crate {

    public int acrossCrate;
    public int upDownCrate;
    Context theContext;

    WindowManager wm = (WindowManager)theContext.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    int width = display.getWidth();


    public Crate() {
    acrossCrate = 650;
    upDownCrate = 650;
    //int width = ;
    //int height = ;

  }
 } 
1个回答

12

使用以下代码

private int getScreenHeight(Context context) {
        int height;

        if (android.os.Build.VERSION.SDK_INT >= 13) {
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            height = size.y;
        } else {
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            height = display.getHeight();  // deprecated
        }

        return height;
    }

getSize()是更好的选择,因为getHeight()和getWidth()在几年前就已经被弃用了。这是对OP问题的更好回答。 - MarsAtomic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接