Android开发之获取屏幕分辨率

在实际开发中,常常会需要根据不同的屏幕分辨率来布局不同的UI组件。那么手机屏幕的分辨率又该如何获取?

下面先来看下实现的效果:

 

实现代码:

01 package com.onmoso.display.demo;
02  
03 import android.app.Activity;
04 import android.os.Bundle;
05 import android.util.DisplayMetrics;
06 import android.widget.TextView;
07  
08 public class DisplayDemoActivity extends Activity {
09     /** Called when the activity is first created. */
10     @Override
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;
18          
19         TextView textView = (TextView)findViewById(R.id.textId);
20         textView.setText("手机屏幕分辨率:"+width+"*"+height);
21     }
22 }
XML:

01 <?xml version="1.0" encoding="utf-8"?>
02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03     android:layout_width="fill_parent"
04     android:layout_height="fill_parent"
05     android:orientation="vertical" >
06  
07     <TextView
08         android:layout_width="fill_parent"
09         android:layout_height="wrap_content"
10         android:text="@string/hello"
11         android:id="@+id/textId"
12         />
13  
14 </LinearLayout>

你可能感兴趣的:(android,UI,xml,layout,手机,encoding)