以编程方式将边距设置为 ConstraintLayout [英] Programmatically set margin to ConstraintLayout
问题描述
我需要在不同的情况下更改由 ConstraintLayout 组成的工具栏的边距.我尝试按照以下方式进行
I need to change margin of toolbar, which was made of ConstraintLayout, in different cases. I tried to do it in following way
ConstraintLayout.LayoutParams newLayoutParams = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
ConstraintLayout.MarginLayoutParams layoutParams = new ConstraintLayout.MarginLayoutParams(newLayoutParams);
layoutParams.setMargins(0, 0, 0, 0);
toolbar.setLayoutParams(newLayoutParams);
但在第二种情况下 layoutParams.setMargins(16, 16, 16, 16);
它没有改变.所以,有人可以给出其他方式或指出错误.感谢您花时间解决我的问题.
but in second case layoutParams.setMargins(16, 16, 16, 16);
it did not change. So, can someone give other way or point to the mistake. Thanks for spending time to my problem.
我尝试使用 newLayoutParams.setMargins(54, 54, 54, 0);
这将边距放在左右两侧,但我仍然需要在它上面放置边距.
I tried to use newLayoutParams.setMargins(54, 54, 54, 0);
this puts margin to left and right, but I still need to put margin on top of it.
推荐答案
终于在@Aksh 的帮助下我发现了我的错误并解决了我的问题.如果有人觉得有用,我会把我的代码放在下面
Finally with help of @Aksh I found my mistake and solve my problem. If someone find it useful, I will put my code bellow
ConstraintLayout.LayoutParams newLayoutParams = (ConstraintLayout.LayoutParams) toolbar.getLayoutParams();
newLayoutParams.topMargin = 0;
newLayoutParams.leftMargin = 0;
newLayoutParams.rightMargin = 0;
toolbar.setLayoutParams(newLayoutParams);
这篇关于以编程方式将边距设置为 ConstraintLayout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!