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>
程序运行效果截图: