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

Android allows you to define the size of user interface components in fixed or relative dimensions in the layout files. If you use fixed sized dimensions, e.g., pixels, your user interface may look fine on a certain device, but the button might be too small on other devices with a higher pixel density.

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 for dip (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.Ui android

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 dpas 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.