https://kotlinlang.org logo
Title
a

Alejandro Moya

03/15/2022, 1:30 PM
Hey Everyone 😄, I have a question about getting xml resources,
fun dimensionResource(@DimenRes id: Int): Dp
returns DP dimensions, but there’s no SP version of it, is there a way to return the SP xml dimensions?
a

Adam Powell

03/15/2022, 1:36 PM
Is this a constant you share in both compose and in view layout xml?
a

Alejandro Moya

03/15/2022, 1:36 PM
yes
I’m working on migrating an existing app from xml layouts to compose and need to use the SP resources to access the font styles sizes
a

Alejandro Moya

03/15/2022, 1:39 PM
I have a set of sizes for tablet and phone
is that accurate?
converting from DP to SP an SP xml resource?
a

Adam Powell

03/15/2022, 1:42 PM
In the fullness of time you'll want to migrate off of using xml resources for size constants, but if you take a look at how the
dimensionResource
function reads android resources you should be able to write what you need here
a

Alejandro Moya

03/15/2022, 1:44 PM
this fits into integrating compose on an existing app, the intention is to completely migrate to compose, but the app needs to work while migrating, there’s an existing codebase that won’t be migrated all at once since it’s way complicated to do
m

mkrussel

03/15/2022, 1:45 PM
I don't know what
dimensionResource
does when loading an sp resources as dp. I was guessing it ignored the unit in the xml and just treated it as dp, but that is probably wrong.
a

Alejandro Moya

03/15/2022, 1:46 PM
@Composable
@ReadOnlyComposable
fun dimensionResource(@DimenRes id: Int): Dp {
    val context = LocalContext.current
    val density = LocalDensity.current
    val pxValue = context.resources.getDimension(id)
    return Dp(pxValue / density.density)
}
that’s the function
m

mkrussel

03/15/2022, 1:48 PM
So I think conversion should work, but like @Adam Powell said it would be easy to implement an Sp version.
I don't think that is an error.
getDimension
loads as pixel value, and then
dimensionResource
converts to
DP
.
a

Alejandro Moya

03/15/2022, 1:52 PM
yes, I deleted the comment as the resulting float is multiplied to return pixels
I’ll have to create an SP version of it
Thanks! 🙏