androidkotlin

Error while adding an Image composable function in Android Studio


I am following the android development course on developer.android.com and wile adding the above composable function I am getting the following error:

None of the following functions can be called with the arguments supplied.

Image(ImageBitmap, String?, Modifier = ..., Alignment = ..., ContentScale = ..., Float = ..., ColorFilter? = ..., FilterQuality = ...) defined in androidx.compose.foundation Image(Painter, String?, Modifier = ..., Alignment = ..., ContentScale = ..., Float = ..., ColorFilter? = ...) defined in androidx.compose.foundation Image(ImageVector, String?, Modifier = ..., Alignment = ..., ContentScale = ..., Float = ..., ColorFilter? = ...) defined in androidx.compose.foundation

According to the course tutorial the error should resolve after including the following import:

import androidx.compose.foundation.Image

This is the the code where i am using the imahge composable:

@Composable
fun GreetingImage(message: String, from: String, modifier: Modifier = Modifier) {
    val image = painterResource(R.drawable.androidparty)
        Image(
            painter = image
        )
}

Solution

  • The Image function has two required parameters, not just one:

    @Composable
    fun Image(
        painter: Painter,
        contentDescription: String?,
        modifier: Modifier = Modifier,
        alignment: Alignment = Alignment.Center,
        contentScale: ContentScale = ContentScale.Fit,
        alpha: Float = DefaultAlpha,
        colorFilter: ColorFilter? = null
    ): Unit
    

    So in addition to setting the painter, you also must provide a contentDescription - that's the string that users with impaired vision will have read to them, since they cannot see what painter you have set:

    @Composable
    fun GreetingImage(message: String, from: String, modifier: Modifier = Modifier) {
        val image = painterResource(R.drawable.androidparty)
        // Make a String resource in res/values/strings.xml
        val contentDescription = stringResource(R.string.androidparty)
        Image(
            painter = image,
            contentDescription = contentDescription
          )
    }