Margins of a LinearLayout, programmatically with dp

后端 未结 6 1899
生来不讨喜
生来不讨喜 2020-12-01 01:12

Is it possible to set the Margins of a LinearLayout, programmatically but not with pixels, but dp?

6条回答
  •  猫巷女王i
    2020-12-01 01:53

    I had the same issue and used this technique to solve it:

    First, I added an xml file to my res/values folder called dimensions.xml. It looks like this:

    
    
      5dip
    
    

    Second, in my code, I got the pixel equivalent of that margin as follows (note I'm using Xamarin so this is C# code, but the pure Java version should be very similar):

    int myMarginPx = Resources.GetDimensionPixelSize(Resource.Dimension.my_margin);
    

    Finally, I create my layout params:

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FillParent, LinearLayout.LayoutParams.WrapContent);
    layoutParams.SetMargins(myMarginPx, myMarginPx, myMarginPx, myMarginPx);
    

提交回复
热议问题