I made a simple program to learn about concatenation in android studio with Kotlin. So, I tried to get a string value from resources in strings.xml as shown below and concatenate with a value
<string name="txt_show">Your lucky number is %1$s</string>
I got warning "Do not concatenate text..." from getString
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val firstNumber = numEditText.text
processButton.setOnClickListener {
val result = concatText(firstNumber.toString().toDouble())
resultView.text = getString(R.string.txt_show, " ") + result.format(2)
}
}
private fun concatText(myNumber: Double): Double {
val luckyNumber = 1.79
return luckyNumber * myNumber
}
private fun Double.format(digits: Int) = java.lang.String.format("%.${digits}f", this)}
By replacing
resultView.text = getString(R.string.txt.show, " ") + result.format(2)
with
val finalResult = result.toInt()<p>
resultView.text = getString(R.string.txt_show, finalResult)<p>
And replace %1$s
to %1$d
in resources of strings.xml
The warning is gone but I got problems, first the result is integer which is not what I expected. It should be double. Second, adding the function format in getString will stop the program with "Unexpected Error..." message on the screen.
How can I solve this problem?
If you have string with some placeholders like:
<string name="price_string">Your price: %d</string>
JAVA
String text = getString(R.string.price_string, 2.5);
KOTLIN
val text = getString(R.string.price_string, 2.5)
.
JAVA:
// Read text
String priceString = getString(R.string.price_string);
// Fill it
String output = String.format(priceString, 2.5);
KOTLIN
// Read text
val priceString = getString(R.string.price_string)
// Fill it
val output = String.format(priceString, 2.5)
// or
val output = priceString.format(2.5)
If you have %s
you have to fill it with String
. Here you have more info: https://developer.android.com/guide/topics/resources/string-resource#formatting-strings
first the result is integer which is not what I expected. It should be double.
Then why did you call toInt
? Just use
resultView.text = getString(R.string.txt_show, result)
and %1$.2f
(or just %.2f
) in the string instead of %1$d
to format to two digits fractional number. You can see it's specified the same as in the format
function in your code. The documentation for format strings (what all of these %d
etc. mean) is at https://developer.android.com/reference/java/util/Formatter.html.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With