Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set negative margin on View programmatically

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?

like image 221
dumazy Avatar asked Aug 29 '13 13:08

dumazy


People also ask

How do you create a negative margin in constraint layout?

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.

Can margin be negative in Android?

Margin values should be positive. Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp".

How do you set margin top programmatically?

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.


1 Answers

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().

like image 173
laalto Avatar answered Sep 19 '22 12:09

laalto