获取视图的边距

如何从活动中获得视图的边距值? 视图可以是任何类型。

经过一段时间的搜索,我找到了获得视图填充的方法,但是在 Margin 上找不到任何东西。有人能帮忙吗?

我试过这种方法,

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

这是可行的,但是在上面的代码中,我假设视图是 LinearLayout。但是即使我不知道视图类型,我也需要获得 margin属性。

66030 次浏览

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

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

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

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)