I have the following string in my strings.xml:
<string name="end_test_msg">Your score is: %1$s%%</string>
I'm using this in a DialogFragment builder as the .setMessage function's parameter (score is a String from a float or int):
class EndTestDialogFragment(percent: Double) : DialogFragment() {
//Converts percent to a string, truncates ".00" if it's a whole number.
private val score: String = when(percent.compareTo(percent.toInt()) == 0) {
true -> percent.toInt().toString()
false -> String.format("%.2f", percent)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val builder = AlertDialog.Builder(it)
builder.setTitle(getString(R.string.end_test_title))
builder.setMessage(getString(R.string.end_test_msg, score))
.setPositiveButton(getString(R.string.ok),
DialogInterface.OnClickListener { dialog, id ->
this.activity?.finish()//Return to the MainActivity
})
// Create the AlertDialog object and return it
builder.setCancelable(false)
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
}
Rather than getting "Your score is: 50%" (or whatever appropriate number) the dialog is showing "Your score is: %1$s%% 50%". It does this regardless of whether score comes from the .toInt()... or the formatted double. What am I doing wrong? It's bizarre to me that I'm seeing both the placeholder and the correctly formatted string.
In case its placement matters, the EndTestDialog class is defined within the Activity that is using it. When I use the exact same formulation within the Activity (but in a TextView, not a Dialog) it displays fine without showing the placeholder.
Please forgive me if I'm overlooking the obvious; I'm very new to Android/Kotlin.
CodePudding user response:
It turned out to be a copy-paste error. I'm so sorry to waste your time; I was accidentally calling a fully qualified version of a similar dialog from another Activity, and not the one defined in the class in question. The two identical classes are now defined in a single file and it is used by both Activities.
Dies of embarrassment.