发布于 2016-04-01 10:17:19 | 209 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

Android移动端操作系统

Android是一种基于Linux的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由Google公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用“安卓”或“安致”。


这篇文章主要介绍了android获取屏幕高度和宽度的实现方法,较为详细的分析了Android获取屏幕高度和宽度的原理与实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了android获取屏幕高度和宽度的实现方法。分享给大家供大家参考。具体分析如下:

我们需要获取Android手机或Pad的屏幕的物理尺寸,以便于界面的设计或是其他功能的实现。下面就介绍讲一讲如何获取屏幕的物理尺寸

下面的代码即可获取屏幕的尺寸。
在一个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程序就支持了多种分辨率,那么就可以得到正确的物理尺寸了。

import android.app.Activity;  

import android.os.Bundle;  

import android.util.DisplayMetrics;  

import android.widget.TextView;  

public class TextCanvasActivity extends Activity {  

    public void onCreate(Bundle savedInstanceState) {  

          super.onCreate(savedInstanceState);  

        //setContentView(new MyView(this));  

            

        //定义DisplayMetrics 对象    

         setContentView(R.layout.main);    

         DisplayMetrics  dm = new DisplayMetrics();    

        //取得窗口属性    

         getWindowManager().getDefaultDisplay().getMetrics(dm);    

          

        //窗口的宽度    

         int screenWidth = dm.widthPixels;    

         

        //窗口高度    

         int screenHeight = dm.heightPixels;           

         TextView textView = (TextView)findViewById(R.id.tv1);           

         textView.setText("屏幕宽度: " + screenWidth + "\n屏幕高度: " + screenHeight);   

    }  

}

希望本文所述对大家的Android程序设计有所帮助。



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务