3

I have seen some people using sp for margins like:

android:layout_marginLeft="40sp"

While many have been using dp, like:

android:layout_marginLeft="40dp"

Could anyone please confirm which is better between these two and which should be used when? Any help would be highly appreciated.

user1903022
  • 1,075
  • 1
  • 13
  • 19

2 Answers2

8

sp for font sizes, dp for everything else. sp stands for Scale-independent Pixels, dp stands for dip=density independent pixels. Detailed explanation

Community
  • 1
  • 1
Mustafa Berkay Mutlu
  • 1,929
  • 1
  • 25
  • 37
0

An XML-defined dimension value. A dimension is denoted by a number followed by a unit of measurement. For instance, 25px, 5in, 10dp and 10sp. When you use sp/dp, your Android applications will be compatible with a wide range of screen densities and resolutions.

PX: is an abbreviation for Pixels, which specifies the actual pixels on the screen.

SP: is an abbreviation for Scale independent pixels. It is the same as the dp unit, but it is additionally scaled according to the user’s font size selection.

DP: A virtual pixel unit used to communicate layout dimensions or location in a density-independent manner while creating UI layout. The density-independent pixel corresponds to one physical pixel on a 160 dpi screen, which is the system’s baseline density for a “medium” density screen. At runtime, the system handles any scaling of the dp units that is required based on the actual density of the screen in use in a transparent manner.

The terms DP and DIP refer to Density Independent Pixels, which are based on the physical density of the screen.

SP: Similar to dp, but also scaled by the user’s font size selection. When choosing font sizes, it is recommended that you use this unit so that they are adjusted for both screen density and user choice.