【问题标题】:How to use different kinds of placeholders in enum classes如何在枚举类中使用不同类型的占位符
【发布时间】: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 a vararg of format argumentsHere 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


【解决方案1】:

如果我理解您的问题,您想定义某种类型的特定分组,并使它们彼此有所区别。

无论如何,我会使用 sealed classes 或具有不同参数的类的简单对象 varargs 的占位符字符串。

【讨论】:

  • 周围有什么例子吗?
猜你喜欢
  • 1970-01-01
  • 2014-07-23
  • 1970-01-01
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 2017-02-03
相关资源
最近更新 更多