Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

margin
ui/ux
interface

How to set a view's padding in Android

Educative Answers Team

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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring