format statement in a string resource file - android

I have strings defined in the usual strings.xml Resource file like this:
<string name="hello_world"> HELLO</string>
Is it possible to define format strings such as the one below
result_str = String.format("Amount: %.2f for %d days ", var1, var2);
in the strings.xml resource file?
I tried escaping the special characters but its not working.

You do not need to use formatted="false" in your XML. You just need to use fully qualified string format markers - %[POSITION]$[TYPE] (where [POSITION] is the attribute position and [TYPE] is the variable type), rather than the short versions, for example %s or %d.
Quote from Android Docs: String Formatting and Styling:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments: %1$s is a
string and %2$d is a decimal integer. You can format the string with
arguments from your application like this:
Resources res = getResources();
String text = res.getString(R.string.welcome_messages, username, mailCount);

You should add formatted="false" to your string resource
Here is an example
In your strings.xml :
<string name="all" formatted="false">Amount: %.2f%n for %d days</string>
In your code:
yourTextView.setText(String.format(getString(R.string.all), 3.12, 2));

Inside file strings.xml define a String resource like this:
<string name="string_to_format">Amount: %1$f for %2$d days%3$s</string>
Inside your code (assume it inherits from Context) simply do the following:
String formattedString = getString(R.string.string_to_format, floatVar, decimalVar, stringVar);
(In comparison to the answer from LocalPCGuy or Giovanny Farto M. the String.format method is not needed.)

Quote from Android Docs:
If you need to format your strings using String.format(String,
Object...), then you can do so by putting your format arguments in the
string resource. For example, with the following resource:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments: %1$s is a string
and %2$d is a decimal number. You can format the string with arguments
from your application like this:
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

For me it worked like that in Kotlin:
my string.xml
<string name="price" formatted="false">Price:U$ %.2f%n</string>
my class.kt
var formatPrice: CharSequence? = null
var unitPrice = 9990
formatPrice = String.format(context.getString(R.string.price), unitPrice/100.0)
Log.d("Double_CharSequence", "$formatPrice")
D/Double_CharSequence: Price :U$ 99,90
For an even better result, we can do so
<string name="price_to_string">Price:U$ %1$s</string>
var formatPrice: CharSequence? = null
var unitPrice = 199990
val numberFormat = (unitPrice/100.0).toString()
formatPrice = String.format(context.getString(R.string.price_to_string), formatValue(numberFormat))
fun formatValue(value: String) :String{
val mDecimalFormat = DecimalFormat("###,###,##0.00")
val s1 = value.toDouble()
return mDecimalFormat.format(s1)
}
Log.d("Double_CharSequence", "$formatPrice")
D/Double_CharSequence: Price :U$ 1.999,90

Related

Can't get rupee symbol to show correctly from strings.xml

So this works fine:
strFoo = "\u20B9" + strBar
But this doesn't
strFoo = R.string.rupee_symbol.toString() + strBar //.toString() is required
//R.string.rupee_symbol.toString() evaluates to some random number 2131755148... which I believe is a character array...
strings.xml
<string name="rupee_symbol">\u20B9 </string>
I can't figure out why it would behave like that, it looks like the same thing...!
You should not concatenate strings with string resources instead, you can use place holder:
<string name="rupee_symbol">\u20B9%s</string>
And use:
strFoo = resources.getString(R.string.rupee_symbol, strBar)
use getString(R.string.rupee_symbol) instead R.string.rupee_symbol.toString()
For example-
String strBar = String.valueOf(100);
String strFoo = getString(R.string.rupee_symbol)+strBar;
textView.setText( strFoo);

How to use decimal numer (Double data type) as placeholder in String resource

I want to use a more than 1 data type inside a placeholder within a String resource but whenever I try to use a demical number as a numerical value, an error is returned.
Kotlin
val currentLocale = Locale.getDefault()
val distanceWalked = 5.2
val numberFormatter: NumberFormat
val amountOut: String
numberFormatter = NumberFormat.getNumberInstance(currentLocale)
amountOut = numberFormatter.format(distanceWalked)
tv.txt = getString(R.string.distance_decimalnumber_placeholder,amountOut,"*")
Stirng resouce
<string name="distance_decimalnumber_placeholder">You have walked %1$d%2$s metres</string>
Expected result
You have walked 5.2* metres
Error
java.util.IllegalFormatConversionException: d != java.lang.Double
Wrong argument type for formatting argument '#1' in distance_decimalnumber_placeholder: conversion is 'd', received String (argument #2 in method call)
First mistake d is for ints
The problem:
You aready converted to string at: amountOut = numberFormatter.format(distanceWalked) you need to replace with string now
Solution: You don`t need to use $f you need to use $s
tv.txt = getString(R.string.distance_decimalnumber_placeholder,amountOut /* this is a string also*/ ,"*")
<string name="distance_decimalnumber_placeholder">You have walked %1$s%2$s metres</string>
I would like to mention two things :
Don't use d for double ... d is treated as int so use f instead of d. So don't use this
<string name="distance_decimalnumber_placeholder">You have walked %1$d%2$s metres</string>
And You don't need a chartype specifier to display * use * after the f like this
<string name="distance_decimalnumber_placeholder">You have walked %1$f* metres</string>
Notice that I have added only one place holder.

Add only 1 char into String

Is it possible to change 1 char into String from code in Kotlin ?
I think yes, but I don't know how.
<string name="carID">Id: </string>
Currently I change whole String like:
carID.text = car.id.toString()
but I want add only number to this ID:
You can convert a char to a string:
val myChar = '1'
val myString = Character.toString(myChar )
Now, you can concat the new string to your other string:
val myIdString = "Id: $myString"
This is of course just the mechanics, you will need to adapt the code as you need and of course there are short-cuts if you want: this was purely for demonstration.
Change your string resource like this:
<string name="carID">Id: %1$s</string>
and you use it:
carID.text = String.format(getString(R.string.carID), "1")
the text will be: Id: 1

how to set text to textfield android with one default value along with an additional value [duplicate]

I have strings defined in the usual strings.xml Resource file like this:
<string name="hello_world"> HELLO</string>
Is it possible to define format strings such as the one below
result_str = String.format("Amount: %.2f for %d days ", var1, var2);
in the strings.xml resource file?
I tried escaping the special characters but its not working.
You do not need to use formatted="false" in your XML. You just need to use fully qualified string format markers - %[POSITION]$[TYPE] (where [POSITION] is the attribute position and [TYPE] is the variable type), rather than the short versions, for example %s or %d.
Quote from Android Docs: String Formatting and Styling:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments: %1$s is a
string and %2$d is a decimal integer. You can format the string with
arguments from your application like this:
Resources res = getResources();
String text = res.getString(R.string.welcome_messages, username, mailCount);
You should add formatted="false" to your string resource
Here is an example
In your strings.xml :
<string name="all" formatted="false">Amount: %.2f%n for %d days</string>
In your code:
yourTextView.setText(String.format(getString(R.string.all), 3.12, 2));
Inside file strings.xml define a String resource like this:
<string name="string_to_format">Amount: %1$f for %2$d days%3$s</string>
Inside your code (assume it inherits from Context) simply do the following:
String formattedString = getString(R.string.string_to_format, floatVar, decimalVar, stringVar);
(In comparison to the answer from LocalPCGuy or Giovanny Farto M. the String.format method is not needed.)
Quote from Android Docs:
If you need to format your strings using String.format(String,
Object...), then you can do so by putting your format arguments in the
string resource. For example, with the following resource:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments: %1$s is a string
and %2$d is a decimal number. You can format the string with arguments
from your application like this:
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
For me it worked like that in Kotlin:
my string.xml
<string name="price" formatted="false">Price:U$ %.2f%n</string>
my class.kt
var formatPrice: CharSequence? = null
var unitPrice = 9990
formatPrice = String.format(context.getString(R.string.price), unitPrice/100.0)
Log.d("Double_CharSequence", "$formatPrice")
D/Double_CharSequence: Price :U$ 99,90
For an even better result, we can do so
<string name="price_to_string">Price:U$ %1$s</string>
var formatPrice: CharSequence? = null
var unitPrice = 199990
val numberFormat = (unitPrice/100.0).toString()
formatPrice = String.format(context.getString(R.string.price_to_string), formatValue(numberFormat))
fun formatValue(value: String) :String{
val mDecimalFormat = DecimalFormat("###,###,##0.00")
val s1 = value.toDouble()
return mDecimalFormat.format(s1)
}
Log.d("Double_CharSequence", "$formatPrice")
D/Double_CharSequence: Price :U$ 1.999,90

Format an array of strings with arguments

I'd like to format an array of strings just like android used to format strings:
Usually we do:
strings.xml
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In some java code:
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
I'm looking for something like:
in some arbitrary xml:
<string-array name="employee">
<item>name: %1$s</item>
<item>post: %2$s</item>
</string-array>
in some java code:
Resources res = getResources();
String[] employee = ArrayString.format(res.getStringArray(R.string.employee), name, post);
Is there an elegant way to do that?
EDIT:
The next pieces of code is a workaround and I'm posting it just to help #Sufian, who asked for it in a comment. It's not a real answer once my question is about format the string array's content and the bellow code is formatting each string separately.
In some misc.xml:
<string-array
name="string_array">
<item>1st position: %1$d</item>
<item>2nd position: %1$d</item>
</string-array>
Then, in java code:
res = getResources();
String[] sa = res.getStringArray(R.array.string_array);
for (int i = 0; i < sa.length; i++ ) {
text += String.format(sa[i], i);
}
Just use:
String text = String.format(res.getStringArray(R.array.myStringArray)[index], param1, param2);
getQuantityString may solve your problem.
Look at quantity strings in http://developer.android.com/guide/topics/resources/string-resource.html
Here's the specific API doc:
http://developer.android.com/reference/android/content/res/Resources.html#getQuantityString(int,%20int,%20java.lang.Object...)

Categories

Resources