Thursday, August 13, 2009

Exercise: Get screen resolution using android.util.DisplayMetrics

android.util.DisplayMetrics is a structure describing general information about a display, such as its size, density, and font scaling.

To use android.util.DisplayMetrics to get resolution:

Create a dummy Android Application, add a TextView in main.xml to display the result.

<TextView
android:id="@+id/strScreenSize"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>

Modify the .java file to read DisplayMetrics

package com.exercise.AndroidScreen;

import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.TextView;

public class AndroidScreenActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
String str_ScreenSize = "The Android Screen is: "
+ dm.widthPixels
+ " x "
+ dm.heightPixels;

TextView mScreenSize = (TextView) findViewById(R.id.strScreenSize);
mScreenSize.setText(str_ScreenSize);
}
}




Related Post:
- Get screen size in DPI

6 comments:

  1. Thanks for this exercise, works great on my HTC desire and all my emulators.

    ReplyDelete
  2. How to get dpi of the device.

    ReplyDelete
  3. it's possible to all version in android?can we apply for all screen resolution?what's the dpi in all screens?

    ReplyDelete