获取屏幕尺寸,以及转换dp和px
/**
* 获取手机屏幕大小
* @author
*
*/
public class WindowWH {
/**
* 获取屏幕宽度
* @param context
* @return int
*/
public static int getWindowWidth(Context pContext){
DisplayMetrics _DisplayMetrics = new android.util.DisplayMetrics();
((Activity)pContext).getWindowManager().getDefaultDisplay().getMetrics(_DisplayMetrics);
return _DisplayMetrics.widthPixels;
}
/**
* 获取屏幕高度
* @param context
* @return int
*/
public static int getWindowHeight(Context pContext){
DisplayMetrics _DisplayMetrics = new android.util.DisplayMetrics();
((Activity)pContext).getWindowManager().getDefaultDisplay().getMetrics(_DisplayMetrics);
return _DisplayMetrics.heightPixels;
}
/**
* 获取状态栏的高度
* @param pContext
* @return int
*/
public static int getStatusHeight(Context pContext) {
int _Statusheight = 50;
int _ResourceId = pContext.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (_ResourceId > 0) {
_Statusheight = pContext.getResources().getDimensionPixelSize(_ResourceId);
}
return _Statusheight;
}
/**
* 获取ActionBar的高度
* @param pContext
* @return
*/
public static int getActionBarHeight(Context pContext) {
int _ActionBarHeight = 0;
TypedValue _TypedValue = new TypedValue();
if (pContext.getTheme().resolveAttribute(android.R.attr.actionBarSize, _TypedValue, true))
{
_ActionBarHeight = TypedValue.complexToDimensionPixelSize(_TypedValue.data,pContext.getResources().getDisplayMetrics());
}
return _ActionBarHeight;
}
/**
* 显示区域的高
* @param pContext
* @return
*/
public static int getDisplayHeight(Context pContext){
return getWindowHeight(pContext) - getStatusHeight(pContext) - getActionBarHeight(pContext);
}
/**
* Android中的Dip转换成像素(px)
* @param pContext
* @param pFloat
* @return
*/
public static int dip2px(Context pContext, float pFloat) {
int value = (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, pFloat, pContext.getResources().getDisplayMetrics()) + 0.5f);
return value;
}
public static int dip2px(float pFloat) {
return dip2px(NewsApplication.sAppContext, pFloat);
}
/**
* 像素(px)转换成Android中的Dip
* @param paramContext
* @param paramFloat
* @return
*/
public static int px2dip(Context pContext, float pFloat) {
return (int) (0.5F + pFloat / pContext.getResources().getDisplayMetrics().density);
}
/**
* 获取NavigationBar的高度
*
* @param pActivity
* @return
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static int getNavigationBarHeight(Context pContext){
try {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
if (((Activity)pContext).getWindow().getDecorView().getSystemUiVisibility() == View.SYSTEM_UI_FLAG_VISIBLE) {
Resources resources = pContext.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
return resources.getDimensionPixelSize(resourceId);
}
}
}
return 0;
} catch (Exception e) {
return 0;
}
}
}