I know how to set margins of a View
programmatically with LinearLayout.LayoutParams
and the method setMargins(int, int, int, int)
but how can I put a negative margin on a view?
Historically, negative margins were not supported in ConstraintLayout. It is changing though—this feature has been added to ContraintLayout 2.1. 0-alpha2 but not available in stable version yet at the time of this writing. In the meantime, we can use a Space widget to accomplish the same task.
Margin values should be positive. Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp".
Set LayoutParams to the view. To set margin to the view create LayoutParams instance, and set margin to the view. LinearLayout. LayoutParams layoutParams = new LinearLayout.
Access the layout params for your parent layout and modify them as you like:
ViewGroup.MarginLayoutParams params =
(ViewGroup.MarginLayoutParams)view.getLayoutParams();
params.topMargin = ...; // etc
// or
params.setMargins(...);
After you've modified the layout, call view.requestLayout()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With