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

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

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

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

 

static intDEFAULT_DENSITY
          The reference density used throughout the system.
 floatdensity
          The logical density of the display.
 intheightPixels
          The absolute height of the display in pixels.
 floatscaledDensity
          A scaling factor for fonts displayed on the display.
 intwidthPixels
          The absolute width of the display in pixels.
 floatxdpi
          The exact physical pixels per inch of the screen in the X dimension.
 floatydpi
          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>


 

程序运行效果截图:

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值