以编程方式更改ConstraintLayout子项的边距和大小

cha*_*hma 13 android android-custom-attributes android-constraintlayout

我正在编写一个自定义视图,以便能够使用自定义XML属性根据这些属性设置视图的边距和大小,一切正常,直到我到达ConstraintLayout的子项获得其边距和大小由自定义值确定的部分.边距没有任何区别,视图保留在其父ConstraintLayout的左上角.可能是什么问题呢?(图像应距离屏幕边界500PXs)

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();
}
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

cha*_*hma 9

我找到了解决办法:很明显Android不采取ConstraintSet.LEFTConstraintSet.RIGHT为正确的参数,并且必须被替换ConstraintSet.STARTConstraintSet.END.

  • 是的,我有一个非常相似的情况,它只适用于ConstraintSet.START和ConstraintSet.END (3认同)