In android you can define the size of the UI elements either in layout files or it can also be acheived in code.We have explained both of mechanisms in the sections below.
Defining the size of UI components in layout files
Fixed or relative dimensions
It is recommended to always use relative dimensions in your Android application.
Using dp as relative dimension
The unit of measurement which should be used is dp
.
dp
is short fordip
(device independent pixel).
dp
refers to one pixel on an Android device with 160dpi (dots per inch). This is the density of the first available Android device (G1). This size is also known asmdpi (medium dots per inch).
If you specify the size in dp
, Android automatically scale your user interface component, depending on the device.
On a mdpi (a.k.a. medium density) device one dp
is the same as one pixel. A dp
on ldpi (low density) device is smaller (approx. 120dip), on a hdpi (high density) device is larger (approx. 240dpi). Therefore a dp
occupies approximately the same physical space on every device.
You can use dp
in your resources, e.g., layout files.
Using sp to scale with the user text preferences
If the unit should scale with text preference settings of the user, choose the sp
unit of measurement. This unit is similar to dp, but it is also scaled by the user preference.
If the users select to increase the font size in this settings, views which use sp
are scaled accordingly.
Defining the size of UI components in source code
The Android API frequently requires you to specify a size in pixels and does not accept dp
as input. In this case you need to transform your desired dp
into actual pixels.
You can use the following method to calculate the right amount of pixels for a dimension specified in dp
.
public int convertToPixelFromDp(int dpInput) {
// get the screen's density scale
final float scale = getResources().getDisplayMetrics().density;
// convert the dps to pixels, based on density scale
return (int) (dpInput * scale + 0.5f);
}
The density for the current device can be queried with the following method call.
getResources().getConfiguration().densityDpi;