Imaginemos un mundo libre

La paz interior comienza en el momento en el que decides no permitir, que ninguna persona o evento, tome el control de tus emociones.

Android Code Snippets: Getting the device metrics

leave a comment »

It’s really important to know the device metrics (Height and width pixels, density, density dpi)  when working on an Android app, specially if you are dealing with fragmentation.

Android has a utility class called DisplayMetrics to get these device properties. Let’s say you need these properties in X activities.  It would be better create a utils class and get the device metrics there.

import android.util.DisplayMetrics;

Your class...
    public static float deviceDensity;
    public static int deviceDensityDpi;
    public static int deviceHeightPixels;
    public static int deviceWidthPixels;

    void getDeviceMetrics(Activity activity)  {
        DisplayMetrics metrics  =  new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        deviceDensity = metrics.density;
        deviceDensityDpi = metrics.densityDpi;
        deviceHeight = metrics.heightPixels;
        deviceWidth = metrics.widthPixels;
    }

...

Written by Ronny Yabar

August 3, 2013 at 1:21 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: