zoukankan      html  css  js  c++  java
  • 【转】android获取屏幕宽度和高度

    原文网址:http://www.cnblogs.com/howlaa/p/4123186.html

    1.

    WindowManager wm = (WindowManager) getContext()
                        .getSystemService(Context.WINDOW_SERVICE);
     
         int width = wm.getDefaultDisplay().getWidth();
         int height = wm.getDefaultDisplay().getHeight();

    2.

    WindowManager wm = this.getWindowManager();
     
         int width = wm.getDefaultDisplay().getWidth();
         int height = wm.getDefaultDisplay().getHeight();

    3、 在一个Activity的onCreate方法中,写入如下代码:

    复制代码
    DisplayMetrics metric = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(metric);
            int width = metric.widthPixels;     // 屏幕宽度(像素)
            int height = metric.heightPixels;   // 屏幕高度(像素)
            float density = metric.density;      // 屏幕密度(0.75 / 1.0 / 1.5)
            int densityDpi = metric.densityDpi;  // 屏幕密度DPI(120 / 160 / 240)
    复制代码

    但是,需要注意的是,在一个低密度的小屏手机上,仅靠上面的代码是不能获取正确的尺寸的。比如说,一部240x320像素的低密度手机,如果运行上述代码,获取到的屏幕尺寸是320x427。因此,研究之后发现,若没有设定多分辨率支持的话,Android系统会将240x320的低密度(120)尺寸转换为中等密度(160)对应的尺寸,这样的话就大大影响了程序的编码。所以,需要在工程的AndroidManifest.xml文件中,加入supports-screens节点,具体的内容如下:

    复制代码
    <supports-screens
                android:smallScreens="true"
                android:normalScreens="true"
                android:largeScreens="true"
                android:resizeable="true"
                android:anyDensity="true" />
    复制代码

    这样的话,当前的Android程序就支持了多种分辨率,那么就可以得到正确的物理尺寸了。

  • 相关阅读:
    FZU 1759 欧拉函数 降幂公式
    51nod 1126 矩阵快速幂 水
    Codeforces Round #325 (Div. 2) D bfs
    Codeforces Round #379 (Div. 2) A B C D 水 二分 模拟
    Codeforces Round #284 (Div. 2)A B C 模拟 数学
    CentOS 7 rsync
    子进程 已安装 pre-removal 脚本 返回了错误号 1或2 与 子进程 已安装 post-installation 脚本 返回了错误号 1或2
    VirtualBox
    Eclipse 安装 HDFS 插件
    docker log 文件 清理
  • 原文地址:https://www.cnblogs.com/wi100sh/p/5462671.html
Copyright © 2011-2022 走看看