android 設定margin
阿新 • • 發佈:2018-11-16
/** * 設定某個View的margin * * @param view 需要設定的view * @param left 左邊距 * @param right 右邊距 * @param top 上邊距 * @param bottom 下邊距 * @return */ public static ViewGroup.LayoutParams setViewMargin(View view, 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); } //設定margin marginParams.setMargins(leftPx, topPx, rightPx, bottomPx); view.setLayoutParams(marginParams); return marginParams; }