Just adding to @David Airam's answer here; the "incorrect" solution he gives is actually correct, but with a bit of tweaking. The XML file should contain:
<string name="resource1">Hello string: %1$s, and hello float: %2$.2f.</string>
Now in the Java code:
String svalue = "test";
float sfloat= 3.1415926;
String sresult = getString(R.string.resource1, svalue, sfloat);
The exception that @David Airam reported is from trying to jam a String
into a format specifier with %f
, which requires a floating point type. Use float
and there is no such exception.
Also, you can use Float.valueOf()
to convert a String to a float in case your input data was originally a string (say, from a EditText
or something). However, you should always try/catch valueOf()
operations and handle the NumberFormatException
case, since this exception is unchecked.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…