Instead of direcly write "red", "yellow" and "green", I would like to get the string from xml.
object Apples {
val apples = listOf("red", "yellow", "green"
)
}
I have tried
val context = LocalContext.current
but it is not working.
It is not possible to access context inside object
.
I suggest you, instead of writing colors directly, use something like this:
object Apples {
val apples = listOf<Int>(
R.string.red,
R.string.yellow,
R.string.green,
)
}
This way, when you need to output any of the values, you simply call stringResource(apples[0])
.
That being said, I might (depending on the use case) solve this by using enum
:
enum class Apples(val nameResId: Int) {
Red(R.string.red),
Yellow(R.string.yellow),
Green(R.string.green)
}
The actual presentation of the string should not be baked into the object itself, but rather the UI should take care of it. While you probably could make a @Composable
function inside the object
, you will create another composable function you won't be able to use outside composable functions.