你好,游客 登录 注册 搜索
背景:
阅读新闻

Android学习笔记之获取手机屏幕大小

[日期:2013-06-14] 来源:Linux社区  作者:nkujerry [字体:大 中 小]

Android手机的屏幕尺寸问题一直是让开发者感觉很头疼的问题,由于各手机厂商所采用的屏幕尺寸不同,user UI接口呈现及布局自然也各自迥异。所以,在开发android手机应用程序时,除了对底层API的掌握之外,最重要的仍是屏幕分辨率概念的理解。

android可设置为随着窗口大小调整缩放比例,但即便如此,手机程序设计人员还是必须清楚地知道手机屏幕的边界,以免缩放之后造成的布局(Layout)变形问题。在android中,只需几行代码就可以取得手机屏幕分辨率,其中的关键则是DisplayMetrics类的应用。

DisplayMetrics类直接继承自Object类,存放在Android.util包下。DisplayMetrics对象记录了一些常用的信息,包含了显示信息、大小、维度和字体等,如下表所示:

static int DEFAULT_DENSITY
The reference density used throughout the system.
float density
The logical density of the display.
int heightPixels
The absolute height of the display in pixels.
float scaledDensity
A scaling factor for fonts displayed on the display.
int widthPixels
The absolute width of the display in pixels.
float xdpi
The exact physical pixels per inch of the screen in the X dimension.
float ydpi
The exact physical pixels per inch of the screen in the Y dimension.

值得一提的是,widthPixels和heightPixels记录了手机屏幕的宽和高,我们使用这两个值便可得到手机屏幕分辨率。注意此处的像素指的是绝对(Absolute)像素,而非相对像素。

下面是获取屏幕分辨率的代码:

public class MainActivity extends Activity
{
    private TextView text=null;
 @Override
 protected void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  super.setContentView(R.layout.activity_main);
  this.text=(TextView)super.findViewById(R.id.text);
  DisplayMetrics dm=new DisplayMetrics();
  super.getWindowManager().getDefaultDisplay().getMetrics(dm);
  String strOpt="手机屏幕分辨率为:"+dm.widthPixels+"*"+dm.heightPixels;
  this.text.setText(strOpt);
 }

}

布局文件非常简单,一个TextView组件即可:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

程序运行效果截图:

Android学习笔记之获取手机屏幕大小

更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款