【问题标题】:Changing ConstraintLayout children's margin and size programmatically以编程方式更改 ConstraintLayout 子级的边距和大小
【发布时间】:2018-02-13 14:09:09
【问题描述】:

我正在编写一个自定义视图,以便能够使用自定义 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 android-constraintlayout android-custom-attributes


    【解决方案1】:

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

    【讨论】:

    • 是的,我遇到了非常相似的情况,只有使用 ConstraintSet.START 和 ConstraintSet.END 才能正常工作
    猜你喜欢
    • 2019-02-08
    • 1970-01-01
    • 2017-03-17
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多