The method
public void setPadding (int left, int top, int right, int bottom)
someview.setPadding(1,1,1,1);
this will give padding with 1px in each side. How can I give 1dip instead of 1px ?
the values fro left , top right and bottom are in pixels , how can I give values programatically in code in dip ?
Thanks
Padding is inside of a View. For example if you give android:paddingLeft=20dp , then the items inside the view will arrange with 20dp width from left. You can also use paddingRight , paddingBottom , paddingTop which are to give padding from right, bottom and top respectively.
The padding is expressed in pixels for the left, top, right and bottom parts of the view. Padding can be used to offset the content of the view by a specific number of pixels. For instance, a left padding of 2 will push the view's content by 2 pixels to the right of the left edge.
Note that padding goes completely around the content: there is padding on the top, bottom, right and left sides (which can be independent). Margins are the spaces outside the border, between the border and the other elements next to this view. In the image, the margin is the grey area outside the entire object.
android:paddingTop =”size in dp”This Attribute is used to specify extra space on the Top Side inside the view as shown in the below output. XML.
Use following code to get pixels from given value in dp
.
Resources res = getResources();
float value = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDP, res.getDisplayMetrics());
where valueInDP is value in dp and this will return corresponding pixel value according to screen density.
or you can use following -
float value = valueInDP * getResources().getDisplayMetrics().density;
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 );
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