Home > Net >  Placeholders not being displayed correctly within string
Placeholders not being displayed correctly within string

Time:06-07

How can the enum class be altered to allow me to display values in my placeholders correctly? At present only the template is being returned. i.e. %1$d and %2$d

Kotlin

val zero: Int = 0
val two: Int = 2

// enum class ItemSizes(@StringRes val nameId: Int, val sizeId: Int) {
//    ItemA(R.string.item_a, R.string.size_placeholder),
//    ItemB(R.string.item_b, R.string.size_placeholder)
// }

// EDIT
enum class ItemSizes(@StringRes val nameId: Int, val sizeId: Int, val placeholderId: Int) {
    ItemA(R.string.item_a, R.string.size_placeholder, 0),
    ItemB(R.string.item_b, R.string.size_placeholder, 2)
}

@Composable
fun <T> MyLazyColumn(
                  lazyItems: Array<T>,
                      item: @Composable RowScope.(item: T) -> Unit,
) {
    LazyColumn(
    ) {
        items(lazyItems) { choice ->
            Row() { item(choice) }
        }
    }
}

Scaffold(
    topBar = {...},
    content = {
        MyLazyColumn(lazyItems = arrayOf(ItemSizes.ItemA,
            ItemSizes.ItemB) {
            Column() {
                Text(text = stringResource(id = it.nameId))
                Text(text = stringResource(id = it.sizeId, it.placeholderId))
            }
        }
    }
)

Current result

enter image description here

Expected result

enter image description here

CodePudding user response:

This code works for me and produces the expected result from your question. Note, this is basically the code you've ended up with in the question, with a few name and formatting changes for clarity/readability.

<resources>
    <string name="item_a">Item A</string>
    <string name="item_b">Item B</string>
    <string name="size_i">Size %1$d</string>
</resources>
enum class ItemSizes(
    @StringRes val nameId: Int,
    @StringRes val sizeId: Int,
    val size: Int,
) {
    ItemA(R.string.item_a, R.string.size_i, 0),
    ItemB(R.string.item_b, R.string.size_i, 2),
}

@Composable
fun <T> MyLazyColumn(
    lazyItems: Array<T>,
    item: @Composable RowScope.(item: T) -> Unit,
) {
    LazyColumn {
        items(lazyItems) { choice ->
            Row { item(choice) }
        }
    }
}

@Composable
fun Example() {
    Scaffold(
        content = {
            MyLazyColumn(lazyItems = arrayOf(ItemSizes.ItemA, ItemSizes.ItemB)) {
                Column {
                    Text(text = stringResource(id = it.nameId))
                    Text(text = stringResource(id = it.sizeId, it.size))
                }
            }
        }
    )
}
  • Related