// -------- start genLayoutParams
//设置默认屏幕宽高,也就是你们UI设计师设置图纸的模板手机
public static int mCommonHeight = 1920;
public static int mCommonWidth = 1080;
public static int NO_PARAMS = -1001;//给定一默认不设置参数标志
//只指定宽高
public static void genLayoutParams(Context mContext, View view,
int height_px, int width_px) {
genLayoutParams(mContext, view, height_px, width_px, NO_PARAMS,
NO_PARAMS, NO_PARAMS, NO_PARAMS);
}
//只指定宽高 与 距离上下左右的margin
public static void genLayoutParams(Context mContext, View view,
int height_px, int width_px, int topMargin_px, int bottomMargin_px,
int leftMargin_px, int rightMargin_px) {
int mScreenHeight = Common.getScreenHeight(mContext);
int mScreenWidth = Common.getScreenWidth(mContext);
ViewGroup.MarginLayoutParams view_params = (MarginLayoutParams) view
.getLayoutParams();
if (NO_PARAMS != height_px) {
view_params.height = (int) (mScreenHeight * round(
(double) height_px / mCommonHeight, 3));
}
if (NO_PARAMS != width_px) {
view_params.width = (int) (mScreenWidth * round((double) width_px
/ mCommonWidth, 3));
}
if (NO_PARAMS != topMargin_px) {
view_params.topMargin = (int) (mScreenHeight * round(
(double) topMargin_px / mCommonHeight, 3));
}
if (NO_PARAMS != bottomMargin_px) {
view_params.bottomMargin = (int) (mScreenHeight * round(
(double) bottomMargin_px / mCommonHeight, 3));
}
if (NO_PARAMS != leftMargin_px) {
view_params.leftMargin = (int) (mScreenWidth * round(
(double) leftMargin_px / mCommonWidth, 3));
}
if (NO_PARAMS != rightMargin_px) {
view_params.rightMargin = (int) (mScreenWidth * round(
(double) rightMargin_px / mCommonWidth, 3));
}
view.setLayoutParams(view_params);
Utils.LOGE(TAG, "view_params.width = " + view_params.width);
Utils.LOGE(TAG, "view_params.height = " + view_params.height);
Utils.LOGE(TAG, "view_params.leftMargin = " + view_params.leftMargin);
Utils.LOGE(TAG, "view_params.rightMargin = " + view_params.rightMargin);
Utils.LOGE(TAG, "设置layoutparams");
}
//dp与px转换
public static int Dp2Px(Context context, double dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
public static int Px2Dp(Context context, double px) {
px = (px / Common.mCommonHeight) * Common.getScreenHeight(context);
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (px / scale + 0.5f);
}
/**
* 提供精确的小数位四舍五入处理。
*
* @param number
* 需要四舍五入的数字
* @param scale
* 小数点后保留几位
* @return 四舍五入后的结果
*/
public static double round(Double number, int scale) {
if (scale < 0) {
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = null == number ? new BigDecimal("0.0") : new BigDecimal(
Double.toString(number));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
// -------- end genLayoutParams
版权声明:本文为博主原创文章,未经博主允许不得转载。