user3422687
user3422687

Reputation: 239

Android Change Margin on Button in Layout

I have a button which on start is placed central and 50 pixels from the top of the layout using the following

android:layout_marginTop="50px"

I need to be able to change this margin depending on what background is being displayed to 100 pixels.

any ideas how i change this

There must be a one liner all the answers i can find involve a long layout params method

Any help is greatly appreciated

Mark

Upvotes: 0

Views: 1263

Answers (2)

Nana Ghartey
Nana Ghartey

Reputation: 7927

Option 1 - Relies on the surrounding/parent layout type, so if the parent layout type is a RelativeLayout, you should use RelativeLayout.LayoutParams instead of LinearLayout.LayoutParams:

LayoutParams params = new LayoutParams(
        LayoutParams.WRAP_CONTENT,      
        LayoutParams.WRAP_CONTENT
);
params.setMargins(0, 100, 0, 0);
myButton.setLayoutParams(params);
//myButton.requestLayout();

Option 2 - Uses a generic method that doesn't rely on the surrounding/parent layout type:

public static void setMargins (View v, int left, int top, int right, int bottom) {
    if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
        p.setMargins(left, top, right, bottom);
        v.requestLayout();
    }
}

Usage:

setMargins(myButton, 0, 100, 0, 0);

Upvotes: 1

Mayur Chudasama
Mayur Chudasama

Reputation: 474

this is for your reference... i hope it will help full to you... and the best use is dp supports for all device and its density pixels

px
Pixels - corresponds to actual pixels on the screen.

in
Inches - based on the physical size of the screen.

mm
Millimeters - based on the physical size of the screen.

pt
Points - 1/72 of an inch based on the physical size of the screen.

dp
Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".

sp
Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference.

Upvotes: 1

Related Questions