public class DpOrPxUtils {
public static View infalte(Context context, @LayoutRes int layoutId, ViewGroup parent) {
return LayoutInflater.from(context).inflate(layoutId, parent, false);
}
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dp2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dp(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
/**
* sp转换成px
*/
public static int sp2px(Context context, float spValue) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}
/**
* px转换成sp
*/
public static int px2sp(Context context, float pxValue) {
float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
/**
* 得到设备屏幕的宽度
*/
public static int getScreenWidth(Context context) {
return context.getResources().getDisplayMetrics().widthPixels;
}
/**
* 得到设备屏幕的高度
*/
public static int getScreenHeight(Context context) {
return context.getResources().getDisplayMetrics().heightPixels;
}
/**
* 得到设备的计算密度
*/
public static float getScreenDensity(Context context) {
return context.getResources().getDisplayMetrics().density;
}
/**
* Whether the Status bar is hidden or not,the method always helps you get
* the height of Status bar.
* 获得状态栏的高度
*
* @param context The context to use. Usually your
* {@link android.app.Application} or
* {@link Activity} object.
* @return Return the height of Status bar.
*/
public static int getStatusHeight(Context context) {
int statusHeight = -1;
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object object = clazz.newInstance();
int id = (Integer) (clazz.getField("status_bar_height").get(object));
statusHeight = context.getResources().getDimensionPixelSize(id);
} catch (Exception e) {
e.printStackTrace();
}
return statusHeight;
}
/**
* 功能描述:获取整块屏幕的高度
*
* @param context
* @return int
*/
public static int getRealScreenHeight(Context context) {
int dpi = 0;
Display display = ((Activity) context).getWindowManager()
.getDefaultDisplay();
DisplayMetrics dm = new DisplayMetrics();
@SuppressWarnings("rawtypes")
Class c;
try {
c = Class.forName("android.view.Display");
@SuppressWarnings("unchecked") Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
method.invoke(display, dm);
dpi = dm.heightPixels;
} catch (Exception e) {
e.printStackTrace();
}
return dpi;
}
/**
* 获取导航栏高度
*
* @param c
* @return
*/
public static int getNavigationBarrH(Context c) {
Resources resources = c.getResources();
int identifier = resources.getIdentifier("navigation_bar_height", "dimen", "android");
return resources.getDimensionPixelOffset(identifier);
}
}
Dp Px
于 2024-09-09 15:38:35 首次发布