'Text Composable dimensionResource not working as fontSize parameter

When I plug in fontSize = dimensionResource(id = R.dimen.textLabelTextSize) where the dimens or 54sp or 60sp depending on the device, I get an error on Text() "None of the following functions can be called with the arguments supplied." But when I put a hard-coded value like 54sp it's fine. What's strange is for the padding modifier dimensionResource (in dp) is working fine.

       Text(
                text = textLabelItem.textLabel,
                modifier = Modifier
                    .padding(
                        start = dimensionResource(id = R.dimen.textLabelPaddingVertical),
                        top = dimensionResource(id = R.dimen.textLabelPaddingHorizontalTop),
                        end = dimensionResource(id = R.dimen.textLabelPaddingVertical),
                        bottom = dimensionResource(id = R.dimen.textLabelPaddingHorizontalBottom)
                    )
                    .background(colorResource(id = R.color.textLabelBg))
                    .border(
                        width = 2.dp,
                        color = colorResource(id = R.color.textLabelBorder),
                        shape = RoundedCornerShape(8.dp)
                    ),
                color = colorResource(id = android.R.color.background_dark),
                fontSize = dimensionResource(id = R.dimen.textLabelTextSize),
                fontWeight = FontWeight.Bold
            )


Solution 1:[1]

The answer is very simple, you just forgot to handle the result from dimensionResource. You need to just use the value of it to have it as float. Then you use sp extension and you are ready to go.

I created my own extension for this:

@Composable
@ReadOnlyComposable
fun fontDimensionResource(@DimenRes id: Int) = dimensionResource(id = id).value.sp

So instead using dimensionResource(R.dimen.your_font_size) use fontDimensionResource(R.dimen.your_font_size)

Final solution:

Text(text = "", fontSize = fontDimensionResource(id = R.dimen.your_font_size))

Solution 2:[2]

The method dimensionResource returns dp value. To get sp value from this add .value.sp at the end like this:

fontSize = dimensionResource(id = R.dimen.textLabelTextSize).value.sp

Solution 3:[3]

It happens because the function dimensionResource returns a Dp value and fontSize works with Sp values.

Currently you can't use it.

Solution 4:[4]

To convert from dp to sp, you need to take into account font scaling - that is the point of using sp for text. This means when the user changes the system font scale, that the app responds to this change.


Does not scale the text

If we request dimensionResource() in kotlin, we get a dp value that is not scaled yet. You can confirm this in the sourcecode where that function is defined to return a Dp:

fun dimensionResource(@DimenRes id: Int): Dp {.....}

A basic conversion to a value.sp does not apply the required scaling, so any solution relying on this type of basic calculation will not work correctly.

unscaledSize = dimensionResource(R.dimen.sp_size).value.sp

(where R.dimen.sp_size is a dimension resource declared with sp sizing)

This does not scale the text size correctly.


Better solution

To do it correctly, we need to look at the DisplayMetrics and the current scaledDensity value, defined as:

/**
* A scaling factor for fonts displayed on the display.  This is the same
* as {@link #density}, except that it may be adjusted in smaller
* increments at runtime based on a user preference for the font size.
*/
public float scaledDensity;

This scaling value must be applied to the dimension that is fetched, to return something that can be used as sp:

val scaledSize = with(LocalContext.current.resources) {
    (getDimension(R.dimen.sp_size) / displayMetrics.scaledDensity).sp
}

Warning: this will only work correctly for dimensions defined as sp!


Handling different dimension types

An even better solution would check what type of dimension resource is being accessed, and would then calculate based on that i.e. dp, sp or px.

This does require working with TypedValue and TypedArray, which makes it a bit more complex, but sample code can be found in the TypedArrayUtils from the MDC Theme Adapter:

internal fun TypedArray.getTextUnitOrNull(
    index: Int,
    density: Density
): TextUnit? {
    val tv = tempTypedValue.getOrSet { TypedValue() }
    if (getValue(index, tv) && tv.type == TypedValue.TYPE_DIMENSION) {
        return when (tv.complexUnitCompat) {
            // For SP values, we convert the value directly to an TextUnit.Sp
            TypedValue.COMPLEX_UNIT_SP -> TypedValue.complexToFloat(tv.data).sp
            // For DIP values, we convert the value to an TextUnit.Em (roughly equivalent)
            TypedValue.COMPLEX_UNIT_DIP -> TypedValue.complexToFloat(tv.data).em
            // For another other types, we let the TypedArray flatten to a px value, and
            // we convert it to an Sp based on the current density
            else -> with(density) { getDimension(index, 0f).toSp() }
        }
    }
    return null
}

Best solution

Ideally, we should not be pulling out resources and converting them when working with Compose. We should be using theme constants instead.

We are probably all on this page because we have some layouts in XML with others in Compose. We are likely going through the conversion process.

The best way to deal with this type of conversion is to use the Material Components MDC-Android Compose Theme Adapter to handle all of these cases.

It works with much more than just a text size calculation and is where we should be aiming to get to as part of our migration to Compose.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TheComposeGuy
Solution 2 prodev
Solution 3 Gabriele Mariotti
Solution 4