我有一个嵌套的LinearLayout(或其他类型的布局),我只想总结一下这个视图的边距/填充的所有水平值及其父级和潜在的祖父母等等。
我只需要此布局的清洁宽度,即window width minus all horizontal margins/paddings
。
我是这样开始的:
private int sumMargins(View view) {
LayoutParams params = (LayoutParams) view.getLayoutParams();
int margins = params.leftMargin + params.rightMargin + view.getPaddingStart() + view.getPaddingEnd();
ViewParent parent = view.getParent();
while (parent != null) {
// here I need to recursively gather all nested parents margins/paddings
// (add them to the `margins` variable)
}
return margins;
}
答案 0 :(得分:0)
ViewGroup.MarginLayoutParams
可让您访问视图的边距。以下代码将遵循视图层次结构,直至顶级DecorView
和左/右边距和填充。
private int sumMargins(View view) {
ViewGroup.MarginLayoutParams marginParams;
int margins = 0;
View decorView = getWindow().getDecorView();
while (view != null && view != decorView) {
marginParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
if (marginParams != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
margins += marginParams.getMarginStart() + marginParams.getMarginEnd() +
view.getPaddingStart() + view.getPaddingEnd();
} else {
margins += marginParams.leftMargin + marginParams.rightMargin +
view.getPaddingLeft() + view.getPaddingRight();
}
}
view = (View) view.getParent();
}
return margins;
}