我正在编写自定义视图,以便能够使用自定义XML属性根据这些属性设置视图的边距和大小,一切正常,直到我到达ConstraintLayout的子项获得的部分#39;他们的边距和大小由自定义值决定。 边距没有任何区别,视图保留在其父ConstraintLayout的左上角。 可能是什么问题呢? (图像应距离屏幕边界500PX)
if (hasCustomWidth || hasCustomHeight || hasCustomTopMargin || hasCustomRightMargin || hasCustomBottomMargin || hasCustomLeftMargin) {
if(((ViewGroup)getParent()) instanceof LinearLayout) {
LinearLayout.LayoutParams newLayoutParams = new LinearLayout.LayoutParams((int) Math.round(customWidth), (int) Math.round(customHeight));
ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) newLayoutParams;
marginLayoutParams.setMargins((int) Math.round(customLeftMargin), (int) Math.round(customTopMargin), (int) Math.round(customRightMargin), (int) Math.round(customBottomMargin));
setLayoutParams(newLayoutParams);
} else if(((ViewGroup)getParent()) instanceof ConstraintLayout) {
ConstraintLayout parentConstraintLayout = (ConstraintLayout)CustomAppCompatImageView.this.getParent();
ConstraintLayout.LayoutParams newLayoutParams = new ConstraintLayout.LayoutParams((int) Math.round(customWidth), (int) Math.round(customHeight));
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(parentConstraintLayout);
constraintSet.connect(CustomAppCompatImageView.this.getId(), ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, 500);
constraintSet.setMargin(CustomAppCompatImageView.this.getId(), ConstraintSet.LEFT, 500);
setLayoutParams(newLayoutParams);
constraintSet.applyTo(parentConstraintLayout);
parentConstraintLayout.invalidate();
} else {
throw new RuntimeException("no listed parent LayoutParams subclass!");
}
invalidate();
}
结果:
答案 0 :(得分:7)
我找到了解决方案:显然Android并没有将ConstraintSet.LEFT
和ConstraintSet.RIGHT
作为正确的参数,必须替换为ConstraintSet.START
和ConstraintSet.END
。