【发布时间】:2022-06-11 05:47:47
【问题描述】:
是否可以在枚举类中为不同类型的占位符启用它?我想使用 1 个具有 1 个占位符的项目,然后使用另一个具有 2 个占位符的项目。我目前的代码似乎只允许我使用 1 个占位符。
strings.xml
<string name="size_placeholder">Size %1$d</string>
<string name="sizes_placeholder_and_placeholder">Sizes %1$d and %2$d</string>
MainActivity.kt
enum class Clothes(@StringRes val nameId: Int, val sizeId: Int, val onePlaceholder: Int, val twoPlaceholders: Int) {
ItemA(R.string.item_a, R.string.size_placeholder, 8),
ItemB(R.string.item_B, R.string.sizes_placeholder_and_placeholder, 0, 2);
}
...
LazyColumn(
state = listState,
modifier = Modifier.weight(1f)
.padding(it)
) {
items(items) {
Column() {
Text(text = stringResource(id = it.nameId))
Text(text = stringResource(id = it.sizeId, it.onePlaceholder, it.twoPlaceholders))
}
}
}
预期结果
更新 (MainActivity.kt)
enum class Clothes(@StringRes val nameId: Int, val sizeId: Int, val myPlaceholder: Int, vararg myPlaceholders: Any) {
ItemA(R.string.item_a, R.string.size_placeholder, 8),
ItemB(R.string.item_B, R.string.sizes_placeholder_and_placeholder, arrayOf(0, 2));
}
...
LazyColumn(
state = listState,
modifier = Modifier.weight(1f)
.padding(it)
) {
items(items) {
Column() {
Text(text = stringResource(id = it.nameId))
Text(text = stringResource(id = it.sizeId, it.myPlaceholders))
}
}
}
【问题讨论】:
-
正如我之前指出的,
stringResource()takes avarargof format arguments。 Here is the source code for it。那么,您尝试使用两种格式参数做了什么,您的具体问题是什么? -
@CommonsWare 我尝试将
val onePlaceholder: Int更改为val onePlaceholder: Any,然后使用“(2, 8)”作为占位符,但这不起作用 -
你试过
stringResource(id = it.sizeId, it.onePlaceholder, it.twoPlaceholders)吗? -
@CommonsWare 我已经更新了我的代码。方向是否正确?
标签: android kotlin enums android-jetpack-compose