Accessing Margins From Code

Nathan Sokalski 4,111 Reputation points
2021-11-21T03:53:44.603+00:00

I have a Button that uses a Style with the following 2 items:

<item name="android:layout_marginLeft">3dp</item>
<item name="android:layout_marginRight">3dp</item>

In my code, I need to access these values (for reading, I do not need to set them in code). How can I do this? Thanks.

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,376 questions
0 comments No comments
{count} votes

Accepted answer
  1. JarvanZhang 23,966 Reputation points
    2021-11-22T03:12:20.957+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    Try getting the LayoutParameters of the button, and then get the margins from the layout params. The value is in pixels, and you can use density to convert it to dp units.

    Here is the sample code, you could refer to it.

       var button = FindViewById<Button>(Resource.Id.btn);  
       button.Click += Button_Click;  
         
       var layoutParams = button.LayoutParameters as Android.Widget.RelativeLayout.LayoutParams;//the LayoutParams type is decided by the button's parent layout  
       var leftMargin = ConvertToDP(layoutParams.LeftMargin);  
       var rightMargin = ConvertToDP(layoutParams.RightMargin);  
         
         
       int ConvertToDP(int pxValue)  
       {  
           var density = Resources.DisplayMetrics.Density;  
           return (int)(pxValue / density);  
       }  
    

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.