Search code examples
androidpixelscaling

Converting automatically from px to sp or dp in Android


I got a layout design which states sizes in px which I save in the dimen resource file.

Is there an automatic way to somehow let Android convert the px unit automatically to sp for strings or dp for other sizes, without the need for me to call a method every single time which converts the unit?

If not, how can I define specific sizes in the layout's xml if all the units are in px?


Solution

  • Unfortunately, px to dp conversion can not be done by the system automatically for you.

    however, you can define several values folders for various screen sizes and define different dimensions(in dp) for each of them.

    refer this question for more details:

    How to define dimens.xml for every different screen size in android?

    Conversion from PX to dp or sp is something you have to do yourself.

    and to conclude, you should not be doing this as most of the time values defined in dp and sp suits to most of the screen sizes, so try that first.