How to set margin of ImageView using code, not xml How to set margin of ImageView using code, not xml android android

How to set margin of ImageView using code, not xml


android.view.ViewGroup.MarginLayoutParams has a method setMargins(left, top, right, bottom). Direct subclasses are: FrameLayout.LayoutParams, LinearLayout.LayoutParams and RelativeLayout.LayoutParams.

Using e.g. LinearLayout:

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);lp.setMargins(left, top, right, bottom);imageView.setLayoutParams(lp);

MarginLayoutParams

This sets the margins in pixels. To scale it use

context.getResources().getDisplayMetrics().density

DisplayMetrics


    image = (ImageView) findViewById(R.id.imageID);    MarginLayoutParams marginParams = new MarginLayoutParams(image.getLayoutParams());    marginParams.setMargins(left_margin, top_margin, right_margin, bottom_margin);    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);    image.setLayoutParams(layoutParams);


All the above examples will actually REPLACE any params already present for the View, which may not be desired. The below code will just extend the existing params, without replacing them:

ImageView myImage = (ImageView) findViewById(R.id.image_view);MarginLayoutParams marginParams = (MarginLayoutParams) image.getLayoutParams();marginParams.setMargins(left, top, right, bottom);