Rectangle 27 2

create layout dynamically and set its parameter as setmargin() will not work directly on an imageView

ImageView im;
im = (ImageView) findViewById(R.id.your_image_in_XML_by_id);
 RelativeLayout.LayoutParams layout = new RelativeLayout.LayoutParams(im.getLayoutParams());
                        layout.setMargins(counter*27, 0, 0, 0);//left,right,top,bottom
                        im.setLayoutParams(layout);
                        im.setImageResource(R.drawable.yourimage)

android - How to set margin of ImageView using code, not xml - Stack O...

android margin imageview
Rectangle 27 321

android.view.ViewGroup.MarginLayoutParams
setMargins(left, top, right, bottom)
LinearLayout.LayoutParams
RelativeLayout.LayoutParams
LinearLayout
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
imageView.setLayoutParams(lp);

This sets the margins in pixels. To scale it use

context.getResources().getDisplayMetrics().density

Note that this sets margin size in PIXELS, is not the same as the dpi unit in the xml of this question.

How can we use a dpi value instead of pixel?

You can scale the px value using context.getResources().getDisplayMetrics().density developer.android.com/reference/android/util/

FrameLayout.LayoutParams

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

android - How to set margin of ImageView using code, not xml - Stack O...

android margin imageview
Rectangle 27 39

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);

What's the deal w/ the last 2 lines? clone the margin params into another params variable? I can confirm it's required :)

a million, billion, trillion thanks for this:)

android:layout_centerHorizontal = "true"
android:layout_alignParentBottom = "true"

android - How to set margin of ImageView using code, not xml - Stack O...

android margin imageview
Rectangle 27 503

LayoutParams
LayoutParams params = new LayoutParams(
        LayoutParams.WRAP_CONTENT,      
        LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
yourbutton.setLayoutParams(params);
RelativeLayout.LayoutParams
LinearLayout.LayoutParams
Resources r = mContext.getResources();
int px = (int) TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        yourdpmeasure, 
        r.getDisplayMetrics()
);

From which package should I import that particular LayoutParams?

@stoefln Why RelativeLayout.LayoutParams and not LinearLayout.LayoutParams?

it depends of your current layout. If you are in LinearLayout, use LinearLayout.LayoutParams. RelativeLayout.LayoutParams otherwise

layout - In Android, how do I set margins in dp programmatically? - St...

android layout button margin
Rectangle 27 495

LayoutParams
LayoutParams params = new LayoutParams(
        LayoutParams.WRAP_CONTENT,      
        LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
yourbutton.setLayoutParams(params);
RelativeLayout.LayoutParams
LinearLayout.LayoutParams
Resources r = mContext.getResources();
int px = (int) TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        yourdpmeasure, 
        r.getDisplayMetrics()
);

From which package should I import that particular LayoutParams?

@stoefln Why RelativeLayout.LayoutParams and not LinearLayout.LayoutParams?

it depends of your current layout. If you are in LinearLayout, use LinearLayout.LayoutParams. RelativeLayout.LayoutParams otherwise

layout - In Android, how do I set margins in dp programmatically? - St...

android layout button margin
Rectangle 27 22

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);

This is the first solution in this list that worked for me. The others screwed up the other params that I had set in the XML, including RelativeLayout params for positioning.

android - How to set margin of ImageView using code, not xml - Stack O...

android margin imageview
Rectangle 27 16

MarginLayoutParams
ImageView image = (ImageView) findViewById(R.id.main_image);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(image.getLayoutParams());
lp.setMargins(50, 100, 0, 0);
image.setLayoutParams(lp);

Weirdly enough I then get "Cannot resolve method setmargins()" which is why I googled for this question and landed here.

android - How to set margin of ImageView using code, not xml - Stack O...

android margin imageview
Rectangle 27 128

MarginLayoutParams params = (MarginLayoutParams) vector8.getLayoutParams();
params.width = 200; params.leftMargin = 100; params.topMargin = 200;

Correct, but no need to set it back, the changed params are automatically reflected. Thus you can remove the line: vector8.setLayoutParams(params);

LayaoutParams usually create confusion while setting margin... So this MarginLayoutParams is very useful. Thanks

This solution worked for me, all others didn't.

i found MarginLayoutParams as new class today #Thanks.

layout - In Android, how do I set margins in dp programmatically? - St...

android layout button margin
Rectangle 27 125

MarginLayoutParams params = (MarginLayoutParams) vector8.getLayoutParams();
params.width = 200; params.leftMargin = 100; params.topMargin = 200;

Correct, but no need to set it back, the changed params are automatically reflected. Thus you can remove the line: vector8.setLayoutParams(params);

LayaoutParams usually create confusion while setting margin... So this MarginLayoutParams is very useful. Thanks

This solution worked for me, all others didn't.

layout - In Android, how do I set margins in dp programmatically? - St...

android layout button margin
Rectangle 27 2

I have myself not used PopUpWindow but the Android docs show a method:

showAtLocation(View parent, int gravity, int x, int y)

There isn't a 4-parameter showAtLocation method in PopupWindow. @yin03 are you sure this is the correct answer?

@Halil there is, the link was incorrect

Android PopUpWindow - How to set margin? - Stack Overflow

android android-layout popupwindow
Rectangle 27 58

private void setMargins (View view, int left, int top, int right, int bottom) {
    if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        p.setMargins(left, top, right, bottom);
        view.requestLayout();
    }
}
setMargins(mImageView, 50, 50, 50, 50);

layout - In Android, how do I set margins in dp programmatically? - St...

android layout button margin
Rectangle 27 57

private void setMargins (View view, int left, int top, int right, int bottom) {
    if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        p.setMargins(left, top, right, bottom);
        view.requestLayout();
    }
}
setMargins(mImageView, 50, 50, 50, 50);

layout - In Android, how do I set margins in dp programmatically? - St...

android layout button margin
Rectangle 27 57

I ended up overriding Fragment.onResume() and grabbing the attributes from the underlying dialog, then setting width/height params there. I set the outermost layout height/width to match_parent. Note that this code seems to respect the margins I defined in the xml layout as well.

@Override
public void onResume() {
    ViewGroup.LayoutParams params = getDialog().getWindow().getAttributes();
    params.width = LayoutParams.MATCH_PARENT;
    params.height = LayoutParams.MATCH_PARENT;
    getDialog().getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);

    super.onResume();
}

@jmaculate - Quick question: when you are casting to (android.view.WindowManager.LayoutParams), what are you casting it from? I was puzzled when choosing the correct import for LayoutParams appearing in the first 3 lines of the function. Ended up choosing (android.view.WindowManager.LayoutParams). Is this supposed to be correct?

@Dev-iL getAttributes() returns a WindowManger.LayoutParams, but in my case I implicitly cast it to ViewGroup.LayoutParams because that's all I need (Effective Java, Item 52) -- I'll edit the question to reflect this

If you need to cast it again to android.view.WindowManager.LayoutParams, it's useless to use ViewGroup.LayoutParams three lines above... You don't gain any flexibility here. Whatever, thank you for this good answer!

This is the best solution. You can even use a specific value of pixels along with MATCH_PARENT or WRAP_CONTENT.

android - How to set DialogFragment's width and height? - Stack Overfl...

android android-fragments android-dialog android-dialogfragment
Rectangle 27 57

I ended up overriding Fragment.onResume() and grabbing the attributes from the underlying dialog, then setting width/height params there. I set the outermost layout height/width to match_parent. Note that this code seems to respect the margins I defined in the xml layout as well.

@Override
public void onResume() {
    ViewGroup.LayoutParams params = getDialog().getWindow().getAttributes();
    params.width = LayoutParams.MATCH_PARENT;
    params.height = LayoutParams.MATCH_PARENT;
    getDialog().getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);

    super.onResume();
}

@jmaculate - Quick question: when you are casting to (android.view.WindowManager.LayoutParams), what are you casting it from? I was puzzled when choosing the correct import for LayoutParams appearing in the first 3 lines of the function. Ended up choosing (android.view.WindowManager.LayoutParams). Is this supposed to be correct?

@Dev-iL getAttributes() returns a WindowManger.LayoutParams, but in my case I implicitly cast it to ViewGroup.LayoutParams because that's all I need (Effective Java, Item 52) -- I'll edit the question to reflect this

If you need to cast it again to android.view.WindowManager.LayoutParams, it's useless to use ViewGroup.LayoutParams three lines above... You don't gain any flexibility here. Whatever, thank you for this good answer!

This is the best solution. You can even use a specific value of pixels along with MATCH_PARENT or WRAP_CONTENT.

android - How to set DialogFragment's width and height? - Stack Overfl...

android android-fragments android-dialog android-dialogfragment
Rectangle 27 2

There is no such thing as a margin-left attribute. You can use a style attribute for this, though:

<xsl:attribute name="style">
    <xsl:value-of select="concat('margin-left: ', $margin, 'px;')"/>
</xsl:attribute>

But using inline styles is rarely a good thing. I suggest you place your tables in a ul/li hierarchy. This way, you can put the margins in your CSS file/<style> section rather than calculating them dynamically:

<xsl:template match="/">
  <ul>
    <xsl:apply-templates />
  </ul>
</xsl:template>     

<xsl:template match="operationLogger">
  <li>
    <table class="normalTable" cols="4">
      <tr class="errorsCollectionTitle">
        <td colspan="4">
          <xsl:value-of select="@name"/>
        </td>
      </tr>
      <xsl:apply-templates select="operationLogEntry"/>
    </table>
    <xsl:if test="operationLogger">
      <ul>
        <xsl:apply-templates select="operationLogger"/>
      </ul>
    </xsl:if>
  </li>
</xsl:template>

thanks alot!!! I cannot believe i wasted so much time for in-line attributes instead of using style! you are a savior!

css - how to set margin dynamically on XSLT - Stack Overflow

css xml xslt
Rectangle 27 5

If you want to change imageview margin but leave all other margins intact.

Get MarginLayoutParameters of your image view in this case: myImageView

MarginLayoutParams marginParams = (MarginLayoutParams) myImageView.getLayoutParams();
  • Now just change the margin you want to change but leave the others as they are: marginParams.setMargins(marginParams.leftMargin, marginParams.topMargin, 150, //notice only changing right margin marginParams.bottomMargin);

android - How to set margin of ImageView using code, not xml - Stack O...

android margin imageview
Rectangle 27 5

You can use this method, in case you want to specify margins in dp:

private void addMarginsInDp(View view, int leftInDp, int topInDp, int rightInDp, int bottomInDp) {
    DisplayMetrics dm = view.getResources().getDisplayMetrics();
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    lp.setMargins(convertDpToPx(leftInDp, dm), convertDpToPx(topInDp, dm), convertDpToPx(rightInDp, dm), convertDpToPx(bottomInDp, dm));
    view.setLayoutParams(lp);
}

private int convertDpToPx(int dp, DisplayMetrics displayMetrics) {
    float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, displayMetrics);
    return Math.round(pixels);
}

android - How to set margin of ImageView using code, not xml - Stack O...

android margin imageview
Rectangle 27 4

ImageView imageView = (ImageView) findViewById(R.id.image_id);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
layoutParams.setMargins(left, top, right, bottom);
imageView.setLayoutParams(layoutParams);

setMargins()'s unit is pixel not dp. If you want to set margin in dp, just inside your values/dimens.xml file create your dimensions like:

<resources>
    <dimen name="right">16dp</dimen>
    <dimen name="left">16dp</dimen>    
</resources>

and access like:

getResources().getDimension(R.dimen.right);

android - How to set margin of ImageView using code, not xml - Stack O...

android margin imageview
Rectangle 27 1

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
 android:padding="10dip"        
    android:background="@color/colorbg">    
</LinearLayout>

padding and margin are different things. @yin03 is asking for margin. You can see the difference between padding and margin if parent view's background color is different that PopupWindow.

Android PopUpWindow - How to set margin? - Stack Overflow

android android-layout popupwindow
Rectangle 27 14

int sizeInDP = 16;

int marginInDp = (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, sizeInDP, getResources()
                    .getDisplayMetrics());
layoutParams = myView.getLayoutParams()
layoutParams.setMargins(marginInDp, marginInDp, marginInDp, marginInDp);
myView.setLayoutParams(layoutParams);
LayoutParams layoutParams = new LayoutParams...
layoutParams.setMargins(marginInDp, marginInDp, marginInDp, marginInDp);
myView.setLayoutParams(layoutParams);

layout - In Android, how do I set margins in dp programmatically? - St...

android layout button margin