Get margin of a View

AndroidAndroid LayoutAndroid View

Android Problem Overview


How can I get the margin value of a View from an Activity? The View can be of any type.

After a bit of searching I found out ways to get padding of a view, but couldn't find anything on Margin. Can anyone help?

I tried something like this,

ViewGroup.LayoutParams vlp = view.getLayoutParams();
int marginBottom = ((LinearLayout.LayoutParams) vlp).bottomMargin;

This works, but in the above code I have assumed the view to be a LinearLayout. But I need to get the margin attribute even when I don't know the view type.

Android Solutions


Solution 1 - Android

try this:

View view = findViewById(...) //or however you need it
LayoutParams lp = (LayoutParams) view.getLayoutParams();

margins are accessible via

lp.leftMargin;
lp.rightMargin;
lp.topMargin;
lp.bottomMargin;

edit: perhaps ViewGroup.MarginLayoutParams will work for you. It's a base class for other LayoutParams.

ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) view.getLayoutParams();

http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html

Solution 2 - Android

Try

ViewGroup.MarginLayoutParams vlp = (MarginLayoutParams) view.getLayoutParams()

vlp.rightMargin
vlp.bottomMargin
vlp.leftMargin
vlp.topMargin

This returned the correct margains for my view atleast.

http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html

Solution 3 - Android

now use this edited code. this will help you

FrameLayout.LayoutParams lp=(FrameLayout.LayoutParams)mainLayout.getLayoutParams();

lp.leftMargin  // for left margin
lp.rightMargin   // for right margin

Solution 4 - Android

As others suggested, layout_margin# is the space between the parent's # edge and your view.

  • # replaces "Left", "Right", "Top" or "Bottom"

Getting/setting margins worked for me with:

ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mView.getLayoutParams();
params.topMargin += 20;
mView.requestLayout();

Of course, my View was indeed a ViewGroup and the parent was a ViewGroup as well. In most cases, you should cast your layout params to the parent's View class LayoutParams (in this case it's ViewGroup and RelativeLayout)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArnab ChakrabortyView Question on Stackoverflow
Solution 1 - AndroidVladimirView Answer on Stackoverflow
Solution 2 - AndroidFreddroidView Answer on Stackoverflow
Solution 3 - Androidilango jView Answer on Stackoverflow
Solution 4 - AndroidmilosmnsView Answer on Stackoverflow