Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Give padding with setPadding with dip unit not px unit

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

like image 582
Lukap Avatar asked Oct 17 '11 12:10

Lukap


People also ask

How to use padding in xml?

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.

What is padding in Android example?

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.

What is the difference between padding and margin in Android?

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.

What is padding top in Android?

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.


2 Answers

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;
like image 158
anujprashar Avatar answered Oct 27 '22 06:10

anujprashar


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 );
like image 41
Pwnstar Avatar answered Oct 27 '22 05:10

Pwnstar