使用ValueAnimator结合String资源实现价格动画遇格式异常如何解决?
问题原因与解决方法
错误根源
你遇到的FormatFlagsConversionMismatchException是因为字符串格式符搭配错误:
- 字符串资源里的
%,s存在矛盾:%,是数字专用的千位分隔符格式标志,必须搭配数字类型转换符(比如%d代表整数),但%s是字符串转换符,两者无法兼容,导致格式解析失败。 - 代码里把
animatedValue转成String传入,进一步加剧了格式不匹配问题。
修正步骤
1. 修正字符串资源文件(strings_format.xml)
把格式符改成%,d,专门用于格式化带千位分隔符的整数:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="price_format">%,d</string> </resources>
2. 修正ValueAnimator代码
直接传入Int类型的动画值,不需要转成String:
private fun setAnimatedTextView( initialValue: Int = 0, finalValue: Int = 0, textView: TextView ) { ValueAnimator.ofInt(initialValue, finalValue).apply { duration = 1_000 addUpdateListener { // 直接强转成Int,因为ofInt生成的动画值就是Int类型 textView.text = requireContext().getString(R.string.price_format, it.animatedValue as Int) } }.start() }
额外说明
如果你的价格是带小数的(比如123,432.13),只需要把格式符改成%,.2f,同时把ValueAnimator换成ofFloat,或者将Int值转成Float处理即可。
内容的提问来源于stack exchange,提问作者CodingBruceLee
相关产品推荐
相关产品推荐

