In my android application I want to change the topMargin of an editText.
The thing is that I want to change it "dp" wise and not pixel wise.
I want to change only the topMaring. Leave the other as is. not set them to zeros ?
programmatically i can set margins in int only?
Set LayoutParams to the view. To set margin to the view create LayoutParams instance, and set margin to the view. LinearLayout. LayoutParams layoutParams = new LinearLayout.
getDisplayMetrics(). density + 0.5f); layoutParams. setMargins(0, marginTopPx, 0, 0); recyclerView. setLayoutParams(layoutParams);
Step 1, to update margin The basic idea is to get margin out and then update it. The update will be applies automatically and you do not need to set it back. To get the layout parameters, simply call this method: LayoutParams layoutParams = (LayoutParams) yourView.
set like follw code:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, convertPixelsToDp(5,this), 0, 0);
editText.setLayoutParams(lp);
and convert Pixels To Dp
public static int convertPixelsToDp(float px, Context context){
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
int dp = px / (metrics.densityDpi / 160f);
return dp;
}
use follow code for changing just one.
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.topMargin = convertPixelsToDp(5,this);
editText.setLayoutParams(params);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
editText.setLayoutParams(lp);
you can not directly set margins using dp programmatically, because .setMargins
method ask pixels not for dp so if you want to give dp's instead of pixels, you should convert dps to pixels.
first create LayoutParams instance:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
then set convert dp to pixels and set margins of the layout like this:
lp.setMargins(left, dpToPx(30), right, bottom);
youredittext.setLayoutParams(lp);
this is the 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);
}
cheers,
Hamad
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With