android學習筆記之擷取手機螢幕大小

來源:互聯網
上載者:User

       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;@Overrideprotected 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>

 

程式運行效果:

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.