创建及使用MarginLayoutParmas
MarginLayoutParams
是继承自ViewGroup.LayoutParmas
,创建时直接new一个对象即可;但一般我们可以这么做:
先获取
View
本身的LayoutParams
对象,检测是否属于一个MarginLayoutParmas
对象,如果是直接修改属性值即可;如果不是,需要以原有布局参数对象为基础,创建一个新的MarginLayoutParams
对象,再进行属性设置
ViewGroup.LayoutParams params = view.getLayoutParams();
ViewGroup.MarginLayoutParams marginParams = null;
//获取view的margin设置参数
if (params instanceof ViewGroup.MarginLayoutParams) {
marginParams = (ViewGroup.MarginLayoutParams) params;
} else {
//不存在时创建一个新的参数
//基于View本身原有的布局参数对象
marginParams = new ViewGroup.MarginLayoutParams(params);
}
创建一个MarginLayoutParams
时,需要以View本身的布局参数对象为基础,否则可能丢失一些原本的布局属性.
通用的设置margin属性的方法
/**
* 设置某个View的margin
*
* @param view 需要设置的view
* @param isDp 需要设置的数值是否为DP
* @param left 左边距
* @param right 右边距
* @param top 上边距
* @param bottom 下边距
* @return
*/
public static ViewGroup.LayoutParams setViewMargin(View view, boolean isDp, int left, int right, int top, int bottom) {
if (view == null) {
return null;
}
int leftPx = left;
int rightPx = right;
int topPx = top;
int bottomPx = bottom;
ViewGroup.LayoutParams params = view.getLayoutParams();
ViewGroup.MarginLayoutParams marginParams = null;
//获取view的margin设置参数
if (params instanceof ViewGroup.MarginLayoutParams) {
marginParams = (ViewGroup.MarginLayoutParams) params;
} else {
//不存在时创建一个新的参数
marginParams = new ViewGroup.MarginLayoutParams(params);
}
//根据DP与PX转换计算值
if (isDp) {
leftPx = getPxFromDpi(left);
rightPx = getPxFromDpi(right);
topPx = getPxFromDpi(top);
bottomPx = getPxFromDpi(bottom);
}
//设置margin
marginParams.setMargins(leftPx, topPx, rightPx, bottomPx);
view.setLayoutParams(marginParams);
return marginParams;
}