android 获取手机大小,android如何获取手机屏幕大小

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)像素,而非相对像素。

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

[java] 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组件即可:

[html]

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" >

android:id="@+id/text"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

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" >

android:id="@+id/text"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

程序运行效果截图:

748f353923665f33deec5075f21daa06.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值