获取屏幕信息

  /**
     * 得到屏幕的宽度
     */
    public void getScreenWidth(){
        DisplayMetrics displayMetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        System.out.println("屏幕的宽度:" + displayMetrics.widthPixels);
    }

    /**
     * 得到屏幕的高度
     */
    public void getScreenHeight(){
        DisplayMetrics displayMetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        System.out.println("屏幕的高度:" + displayMetrics.heightPixels);
    }

    /**
     * dp转px
     * @param dp
     */
    public void dp2px(float dp){
        float px = dp* Resources.getSystem().getDisplayMetrics().density;
        System.out.println("dp转化为px:" + px);
    }

    /**
     * 得到状态栏的高度
     * 该方法在onCreate中获取之为0
     */
    public int getStatusBarHeight1(){
        Rect frame = new Rect();
        this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusHeight = frame.top;
        System.out.println("状态栏的高度:" + statusHeight);
        return statusHeight;
    }

    /**
     * 得到状态栏的高度
     */
    public void getStatusBarHeight2(View view){
        Class c = null;
        Object obj = null;
        Field field = null;
        int x = 0;
        int statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = getResources().getDimensionPixelSize(x);
            System.out.println("状态栏的高度:" + statusBarHeight);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到标题栏的高度
     */
    public void getTitleBarHeight(){
        int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
        int titleBatHeight = contentTop - getStatusBarHeight1();
        System.out.println("标题栏的高度" + titleBatHeight);
    }

    /**
     * 判断是否为平板
     */
    public boolean isTablet(){
       return (this.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)>=Configuration.SCREENLAYOUT_SIZE_LARGE;
        

    }

你可能感兴趣的:(android)