歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android學習筆記之獲取手機屏幕大小

Android學習筆記之獲取手機屏幕大小

日期:2017/3/1 9:55:59   编辑:Linux編程

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 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved