Give padding using setPadding with dip unit not px module

Method

public void setPadding (int left, int top, int right, int bottom) someview.setPadding(1,1,1,1); 

this will give a registration with 1px on each side. How can I give 1dip instead of 1px?

the values ​​on the left, top right and bottom are in pixels, how can I give values ​​programmatically in code in dip?

thanks

+6
source share
3 answers

Use the following code to get pixels from a given value in dp .

 Resources res = getResources(); float value = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDP, res.getDisplayMetrics()); 

where valueInDP is the value in dp, and this will return the corresponding pixel value in accordance with the density of the screen.

or you can use the following -

 float value = valueInDP * getResources().getDisplayMetrics().density; 
+19
source

What is the difference between "px", "dp", "dip" and "sp" on Android?

 float scale = context.getResources().getDisplayMetrics().density; int dpAsPixels = (int) (your_dp_goes_here * scale + 0.5f); view.setPadding(dpAsPixels , dpAsPixels , dpAsPixels , dpAsPixels ); view.setPaddingRelative(dpAsPixels , dpAsPixels , dpAsPixels , dpAsPixels ); 
+1
source
 getListView().setPadding(50,50,50,50); 
0
source

Source: https://habr.com/ru/post/899454/


All Articles