Trusted answers to developer questions

How to set a view's padding in Android

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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:

svg viewer

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

<LinearLayout
    android:paddingTop="30dp"
    android:paddingBottom="30dp"
>

Programmatic approach

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

  1. Get the view to where you want to add padding:
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
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?