Home » Android » Android negative margin does not work

Android negative margin does not work

Posted by: admin May 14, 2020 Leave a comment


I have encountered a problem when i try to give a negative left margin to a LinearLayout.
The negative margin does not appear.
Here is my code

HorizontalScrollView hview = new HorizontalScrollView(context); //  HorizontalScrollView is the outer view   
RelativeLayout.LayoutParams hs_lot_params = new RelativeLayout.LayoutParams(164, 164);
hs_lot_params.setMargins(100, 100, 0, 0); // set the positions

ImageView image = new ImageView(context);
LinearLayout.LayoutParams img_lot_params = new LinearLayout.LayoutParams(164, 164);
img_lot_params.setMargins(0, 0, 0, 0);

LinearLayout ll = new LinearLayout(this);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(164, 164);
layoutParams.setMargins(-132, 0, 0, 0);
ll.addView(image, img_lot_params);
hview.addView(ll, layoutParams);

Note: my plan is to scroll the image from left to right.
First, the left part of the image is hidden and can scroll to right to see the full image

How to&Answers:
 ViewGroup.MarginLayoutParams params =
 (ViewGroup.MarginLayoutParams)view.getLayoutParams(); params.topMargin = -100;


Negative margins should work in LinearLayout and RelativeLayout. What you probably need, is to scroll the HorizontalScrollView with scrollBy(int x, int y) or scrollTo(int x, int y) to achieve the “peek and scroll” effect you described.

Also keep in mind that using raw pixel units is generally a bad idea as the actual size will depend on the pixel density of the screen. Prefer dp measurements instead.