繁体   English   中英

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

[英]Changing ConstraintLayout children's margin and size programmatically

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

结果:

在此输入图像描述

我找到了解决方案:显然Android并没有将ConstraintSet.LEFTConstraintSet.RIGHT作为正确的参数,必须用ConstraintSet.STARTConstraintSet.END替换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM