在 Android ConstraintLayout 中,有时会遇到在代码中设置视图的 topMargin 无效的情况,而在 layout.xml 中却可以正常设定。

这可能是因为在代码中设置的 topMargin 值被后续的 ConstraintLayout 约束覆盖了。

解决方案:

在代码中设置 ConstraintLayout 的约束条件,例如:

ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) view.getLayoutParams();
layoutParams.topMargin = 100;
layoutParams.topToBottom = R.id.some_other_view;
view.setLayoutParams(layoutParams);

其中,topToBottom 指定了当前视图的顶部应该连接到某个其他视图的底部,这样就可以保证 topMargin 生效了。

Android ConstraintLayout 视图 topMargin 无效解决方法

原文地址: https://www.cveoy.top/t/topic/kJ8t 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录