android - 如何在字符串资源中使用十进制数(Double 数据类型)作为占位符

标签 android kotlin android-resources

我想在字符串资源中的占位符内使用超过 1 种数据类型,但每当我尝试使用小数作为数值时,都会返回错误。

Kotlin

val currentLocale = Locale.getDefault()
val distanceWalked = 5.2
val numberFormatter: NumberFormat
val amountOut: String
numberFormatter = NumberFormat.getNumberInstance(currentLocale)
amountOut = numberFormatter.format(distanceWalked)

tv.txt = getString(R.string.distance_decimalnumber_placeholder,amountOut,"*")

搅拌资源
<string name="distance_decimalnumber_placeholder">You have walked %1$d%2$s metres</string>

预期结果

你已经走了 5.2* 米

错误

java.util.IllegalFormatConversionException: d != java.lang.Double

Wrong argument type for formatting argument '#1' in distance_decimalnumber_placeholder: conversion is 'd', received String (argument #2 in method call)

最佳答案

第一个错误d用于整数

问题:

您已在以下位置转换为字符串:amountOut = numberFormatter.format(distanceWalked)你现在需要用字符串替换

解决方法:不需要使用$f您需要使用 $s

tv.txt = getString(R.string.distance_decimalnumber_placeholder,amountOut /* this is a string also*/ ,"*")
<string name="distance_decimalnumber_placeholder">You have walked %1$s%2$s metres</string>

关于android - 如何在字符串资源中使用十进制数(Double 数据类型)作为占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61466816/

相关文章:

android - 如何获取 View ID 的字符串表示形式

android - 防止 WebView 在 Android 中加载 URL(React Native)

android - 向 requestLocationUpdates intentService 发送额外信息会中断位置更新

kotlin - 组合 Flow 和非 Flow api 响应 Kotlin

java - Android - 更改背景资源两次,中间暂停

Android 布局错误 : "Resource id <res_id> is not of type STYLE (instead attr)"

java - Android dalvikvm-heap : Clamp target GC heap

android - AppCompat升级到v22.1.0版本后获取AppCompat不支持当前主题功能异常问题

java - 如何以编程方式从 Android 获取自定义 ROM/Android 操作系统名称

android - OnTouchListerner 不应将打开 DrawerLayout 的滑动解释为长按