Reputation: 12424
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?
Upvotes: 2
Views: 2005
Reputation: 6968
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.
Upvotes: -1
Reputation: 3973
if you read here you will understand that what you want isn't the best solution.
I would suggest to you to change everything px to dp and then put those on the files
most probably your app will work for more than one density screens so the pixel way is very bad choice
Designing layouts for dp
When designing layouts for the screen, calculate an element’s measurements in dp:
dp = (width in pixels * 160) / density
For example, a 32 x 32 px icon with a screen density of 320 equals 16 x 16 dp.
Update
unfortunately what you want cannot be happen. You will have to generate different dp values for different density screens. Read also how to support diffent screen densities from the official documentation
Upvotes: 1
Reputation: 494
You need to call a function all the time, or you need to create custom views that extends the views and override the size/textSize function that converts them automatically
class CustomTextView : AppCompatTextView {
override fun setTextSize(size: Float) {
// do the convertion here
super.setTextSize(size)
}
override fun setTextSize(unit: Int, size: Float) {
// or here
super.setTextSize(unit, size)
}
}
and you will probably need to extend every view that has been using dimens if you don't want to write a function all the time.
Upvotes: 1