- Object lp = view.getLayoutParams();
- // The following instanceof check will fail if we have not previously
- // added the label to the container (Why?)
- if (lp instanceof ViewGroup.MarginLayoutParams) {
- marginLayoutParams = (ViewGroup.MarginLayoutParams) lp;
- defaultLabelMarginInDp = dpToPx(view, DEFAULT_LABEL_MARGIN);
- }
复制代码 根据源码,标签只有在特定的布局中才会有margin,否则就是0不生效。
ViewGroup.MarginLayoutParams 是 Android 布局系统中一个 用于描述视图外边距(margin) 的参数类。它继承自 ViewGroup.LayoutParams,在其基础上新增了对四个方向的 margin 支持。
如何与布局类型配合?你不能随便用 MarginLayoutParams ——它必须与父容器兼容。常见情况如下: | 父容器(ViewGroup) | 它的 LayoutParams 实际类型 | 是否支持 margin | | LinearLayout | LinearLayout.LayoutParams extends MarginLayoutParams | ✅ 是 | | RelativeLayout | RelativeLayout.LayoutParams extends MarginLayoutParams | ✅ 是 | | ConstraintLayout | ConstraintLayout.LayoutParams extends MarginLayoutParams | ✅ 是 | | FrameLayout | FrameLayout.LayoutParams extends MarginLayoutParams | ✅ 是 | | ViewGroup(纯粹) | ViewGroup.LayoutParams | ❌ 否 |
|