【问题标题】:how to display string with paramters in Kotlin/android setText without string concantenation?如何在没有字符串连接的情况下在 Kotlin/android setText 中显示带有参数的字符串?
【发布时间】:2021-05-02 17:15:14
【问题描述】:

我使用以下内容在字符串中输出 6 个双精度数,使用字符串连接。为我工作,但我想这是不好的做法(setText 中的字符串连接)。

allUpM_TextView.setText(
"Mass [kg]: %.0f".format(AllUpM) + " Mass/V [kg/m2]: %.3f".format(MperV) +
"\nMax Alt [m]: %.1f".format(Alt) +
"\nTemp [deg C]: %.1f".format(Temp_a) +
"\nPres [mBar]: %.1f".format(Pres_a) +
"\nLift [kg]: %.1f".format(Lift) )

所以我想用一个资源字符串来做:

 <string name="outputTxt">Mass [kg]: %1$s Mass/V [kg/m2]: %2$s
                        \nMax Alt [m]: %3$s
                        \nTemp [deg C]: %4$s  nPres [mBar]: %5$s
                        \nLift [kg]: %6$s</string>

val string = getString(R.string.outputTxt,
        AllUpM.toString(),
        MperV.toString(),
        Alt.toString(),
        Temp_a.toString(),
        Pres_a.toString(),
        Lift.toString()
        )

allUpM_TextView.setText(string)

双精度输出为全精度。

如何实现 Double 的某些格式,例如“%.1f”或“%.3f”?

在 30 年前最后一次编写 Fortan 后,对使用第一个 Android 应用程序的人的任何帮助。

【问题讨论】:

标签: android string kotlin formatting double


【解决方案1】:
fun Double.toFormattedString(n : Int) : String {
    return "%.${n}f".format(this).toString() // not tested, maybe toString isn't required
}

这将帮助您获得 n 位小数(称为扩展函数,以防您以前没有见过该语法)

然后在每个 double 上使用它而不是调用 toString:

val string = getString(R.string.outputTxt,
        AllUpM.toFormattedString(2),
        MperV.toFormattedString(2),
        Alt.toFormattedString(2),
        Temp_a.toFormattedString(2),
        Pres_a.toFormattedString(2),
        Lift.toFormattedString(2)
        )

allUpM_TextView.setText(string)

【讨论】:

    猜你喜欢
    • 2015-06-02
    • 2021-02-09
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多