Get margin of a View

前端 未结 4 995
遇见更好的自我
遇见更好的自我 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:52

    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

提交回复
热议问题