Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
            )
like image 856
galaxigirl Avatar asked May 13 '21 15:05

galaxigirl


People also ask

How do you change Text size in compose?

To change font size of Text composable in Android Jetpack Compose, pass a required font size value for the optional fontSize parameter of Text composable. Make sure to import sp , as shown in the above code snippet, when you are assign fontSize property with scale-independent pixels.

How do I change the Text color in compose?

To change color of Text composable in Android Jetpack Compose, pass a required Color value for the optional color parameter of Text composable.

How do I make Text bold in compose?

Android Compose – Change Text to Bold To change font weight of Text composable to Bold, in Android Jetpack Compose, pass FontWeight. Bold for the optional fontWeight parameter of Text composable.

Why doesn't dimensionresource work with SP text size?

This does not work. When the user changes default device text size, this does not change the text size. It happens because the function dimensionResource returns a Dp value and fontSize works with Sp values. Currently you can't use it. @galaxigirl Because the function currently works only with Dp.

How to change font size of text in Android jetpack compose?

How to change Font Size of Text in Android Jetpack Compose? To change font size of Text composable in Android Jetpack Compose, pass a required font size value for the optional fontSize parameter of Text composable. Make sure to import sp, as shown in the above code snippet, when you are assign fontSize property with scale-independent pixels.

How do I use the fontfamily in text composable functions?

Configure the FontFamily to be used in your Text composable function and that’s it. text = "Hello World!" You can also define Typography to use your FontFamily . fontSize = ... letterSpacing = ... ... ... ...

What is the difference between the style parameter and fontfamily parameter?

The style parameter allows to set an object of type TextStyle and configure multiple parameters, for example shadow. Shadow receives a color for the shadow, the offset, or where it is located in respect of the Text and the blur radius which is how blurry it looks. Text has a fontFamily parameter to allow setting the font used in the composable.


Video Answer


3 Answers

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))
like image 186
TheComposeGuy Avatar answered Oct 19 '22 11:10

TheComposeGuy


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

Currently you can't use it.

like image 21
Gabriele Mariotti Avatar answered Oct 19 '22 10:10

Gabriele Mariotti


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.

like image 4
Richard Le Mesurier Avatar answered Oct 19 '22 10:10

Richard Le Mesurier