you cannot set fields directly using dp programmatically, because the .setMargins method sets pixels not for dp, so if you want to give dp instead of pixels, you must convert dps to pixels. first create an instance of LayoutParams:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
then set to convert dp to pixels and set the layout fields as follows:
lp.setMargins(left, dpToPx(30), right, bottom); youredittext.setLayoutParams(lp);
This is a conversion method from pixels to dp and dp to pixels:
public static int dpToPx(int dp) { return (int) (dp * Resources.getSystem().getDisplayMetrics().density); } public static int pxToDp(int px) { return (int) (px / Resources.getSystem().getDisplayMetrics().density); }
amuses
Hamad
Hamad
source share