Android基础篇-自动获取屏幕的尺寸及密度

有的时候我们需要获取设备的尺寸以及密度,Android是提供了相应的API的

        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;  // 屏幕宽度(像素)
        int height = metric.heightPixels;  // 屏幕高度(像素)
        float density = metric.density;  // 屏幕密度(0.75 / 1.0 / 1.5)
        int densityDpi = metric.densityDpi;  // 屏幕密度DPI(120 / 160 / 240)

上面的代码在一些低密度的手机上是不起作用的,为此我们必须在配置文件中加入以下代码:

        <supports-screens
            android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:resizeable="true"
            android:anyDensity="true" />

 获取设备信息工具类:

package org.vhow.paintpad.helper;

import android.app.Activity;
import android.util.DisplayMetrics;

/**
 * ScreenInfo.java Use this class to get the information of the screen.
 * 
 * 获取设备的相关信息 
 */
public class ScreenInfo
{
    Activity activity;
    int widthPixels;//设备的宽
    int heightPixels;//设备的高

    /**
     * @param activity
     *            an instance of PaintPadActivity
     */
    public ScreenInfo(Activity activity)
    {
        this.activity = activity;
        getDisplayMetrics();
    }

    private void getDisplayMetrics()
    {
        DisplayMetrics dm = new DisplayMetrics();

        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        this.widthPixels = dm.widthPixels;
        this.heightPixels = dm.heightPixels;
    }

    /**
     * @return the number of pixel in the width of the screen.
     */
    public int getWidthPixels()
    {
        return widthPixels;
    }

    /**
     * @return the number of pixel in the height of the screen.
     */
    public int getHeightPixels()
    {
        return heightPixels;
    }
}

 同时可以直接把它放在Application的子类里面:

public class App extends Application {

    public static String AGENT_URL;
    public static int WIDTH;
    public static int HEIGHT;
    public static float DENSITY;
    
    @Override
    public void onCreate() {
        super.onCreate();
        
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        WIDTH = metrics.widthPixels;
        HEIGHT = metrics.heightPixels;
        DENSITY = metrics.density;
    }
    
    @Override
    public void onTerminate() {
        super.onTerminate();
    }
    
}

 

 

posted @ 2012-05-10 16:22  暗殇  阅读(493)  评论(0编辑  收藏  举报