Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically set margin to 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); 

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.

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.

like image 813
Asset Bekbossynov Avatar asked Sep 03 '18 10:09

Asset Bekbossynov


Video Answer


2 Answers

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); 
like image 161
Asset Bekbossynov Avatar answered Sep 18 '22 23:09

Asset Bekbossynov


good way to add margin to a view in constraintlayout

val constraintSet = ConstraintSet() constraintSet.clone(constraintLayoutId) val marginTop = context.getDimension(10f) constraintSet.setMargin(R.id.tv_user, ConstraintSet.TOP, marginTop) constraintSet.applyTo(constraintLayoutId)  fun Context.getDimension(value: Float): Int {     return TypedValue.applyDimension(     TypedValue.COMPLEX_UNIT_DIP, value, this.resources.displayMetrics).toInt() } 
like image 21
Tobi Oyelekan Avatar answered Sep 20 '22 23:09

Tobi Oyelekan