Padding in Android is used to add a blank space between a view and its contents. Margins, on the other hand, are used to add a space between two different views. The following illustration will help to clarify the difference between the two:
Add an attribute for the padding to your view’s tag in the layout XML file. The code below adds top and bottom padding of dp for the LinearLayout
:
<LinearLayout
android:paddingTop="30dp"
android:paddingBottom="30dp"
>
Padding can also be added through the Java code of an activity:
Button btn = findViewById(R.id.btn_id);
setPadding(left, top, right, bottom)
method on the view to set the padding. The integers passed as parameters to this function are the number of pixels (px), which are different from the density-independent pixels (dp or dip).The pixel density of a screen varies across devices. To achieve consistent physical size, dp is the preferred unit for margins, padding, and other objects’ sizes. Calculate dp with the following formula:
dp = px * context.getResources().getDisplayMetrics().density
btn.setPadding(5, 10, 5, 10);
Free Resources