gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:43:31 30 4
gpt4 key购买 nike

我正在编写一个自定义 View ,以便能够使用自定义 XML 属性来根据这些属性设置 View 的边距和大小,一切正常,直到我到达 ConstraintLayout 的子级获得其边距和大小的部分自定义值。边距没有任何区别, View 停留在其父 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();
}

结果:

enter image description here

最佳答案

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

关于android - 以编程方式更改 ConstraintLayout 子项的边距和大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46052263/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com