Related Tags

margin
ui/ux
interface

# How to set a view's padding in Android

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:

## Syntax

### Declarative approach

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 $30$dp for the LinearLayout:

<LinearLayout
>


### Programmatic approach

Padding can also be added through the Java code of an activity:

Button btn = findViewById(R.id.btn_id);

1. Use the 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);


RELATED TAGS

margin
ui/ux
interface