Margins of a LinearLayout, programmatically with dp
Solution 1:
You can use DisplayMetrics and determine the screen density. Something like this:
int dpValue = 5; // margin in dips
float d = context.getResources().getDisplayMetrics().density;
int margin = (int)(dpValue * d); // margin in pixels
As I remember it's better to use flooring for offsets and rounding for widths.
Solution 2:
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:
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<dimen name="my_margin">5dip</dimen>
</resources>
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);
Solution 3:
You can convert dp to px, for example convert 5dp to px:
Resources r = mContext.getResources();
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, r.getDisplayMetrics());
Solution 4:
The following method works for me for converting pixels to dp:
int pixelToDP(int pixel) {
final float scale = RaditazApplication.getInstance().getResources().getDisplayMetrics().density;
return (int) ((pixel * scale) + 0.5f);
}
Solution 5:
convert DP to Pixel value
int Whatever_valueInDP=10;//value in dp
int Value_In_Pixel= (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, Whatever_valueInDP, getResources()
.getDisplayMetrics());