安卓常用工具类-ControlsUtils【设备、尺寸相关的工具类】

package com.example.burro.demo.appframework.util;

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

/**设备,dp-px转换类
 * Created by burro on 17-2-23.
 */
public class ControlsUtils {

    private static DisplayMetrics _dm = null;

    private static DisplayMetrics getDm(Activity activity) {
        if (_dm == null) {
            _dm = new DisplayMetrics();
            activity .getWindowManager().getDefaultDisplay().getMetrics(_dm);
        }
        return _dm;
    }

    public static float getDensity(Activity activity) {
        return  getDm(activity).density;
    }

    public static int getScreenWidthPx(Activity activity) {
        return getDm(activity).widthPixels;
    }

    public static int getScreenHeightPx(Activity activity) {
        return getDm(activity).heightPixels;
    }

    public static int getScreenWidthDp(Activity activity) {
        return px2Dp(activity, getDm(activity).widthPixels);
    }

    public static int getScreenHeightDp(Activity activity) {
        return px2Dp(activity, getDm(activity).heightPixels);
    }

    public static int px2Dp(Activity activity, int pxValue) {
        final float scale = getDm(activity).density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int dp2Px(Activity activity, int dpValue) {
        final float scale = getDm(activity).density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int getViewHeight(final View view) {
        int _height = -1;
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        _height = view.getMeasuredHeight();
        return _height;
    }

    public static int getViewWidth(final View view) {
        int _width = -1;
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        _width = view.getMeasuredWidth();
        return _width;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值