在实际开发中,常常会需要根据不同的屏幕分辨率来布局不同的UI组件。那么手机屏幕的分辨率又该如何获取?
下面先来看下实现的效果:
实现代码:
01 | package com.onmoso.display.demo; |
03 | import android.app.Activity; |
04 | import android.os.Bundle; |
05 | import android.util.DisplayMetrics; |
06 | import android.widget.TextView; |
08 | public class DisplayDemoActivity extends Activity { |
09 | /** Called when the activity is first created. */ |
11 | public void onCreate(Bundle savedInstanceState) { |
12 | super .onCreate(savedInstanceState); |
13 | setContentView(R.layout.main); |
14 | DisplayMetrics dm = new DisplayMetrics(); |
15 | getWindowManager().getDefaultDisplay().getMetrics(dm); |
16 | int width = dm.widthPixels; |
17 | int height = dm.heightPixels; |
19 | TextView textView = (TextView)findViewById(R.id.textId); |
20 | textView.setText( "手机屏幕分辨率:" +width+ "*" +height); |
XML:
01 | <? xml version = "1.0" encoding = "utf-8" ?> |
03 | android:layout_width = "fill_parent" |
04 | android:layout_height = "fill_parent" |
05 | android:orientation = "vertical" > |
08 | android:layout_width = "fill_parent" |
09 | android:layout_height = "wrap_content" |
10 | android:text = "@string/hello" |
11 | android:id = "@+id/textId" |