17

我正在编写一个自定义视图,以便能够使用自定义 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();
}

结果:

在此处输入图像描述

4

1 回答 1

10

我找到了解决方案:显然 Android 不接受ConstraintSet.LEFTandConstraintSet.RIGHT作为正确的参数,必须用ConstraintSet.STARTand替换ConstraintSet.END

于 2017-09-05T13:16:45.107 回答