Get margin of a View

前端 未结 4 989
遇见更好的自我
遇见更好的自我 2021-01-31 13:28

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\'

4条回答
  •  清歌不尽
    2021-01-31 13:45

    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)

提交回复
热议问题