I have a piece of code where I'm trying to change the language in my app, using a Spinner View Component. While working with this, I've come to realize that I'm probably not using the most smooth method, but more intrestingly, I've noticed that two strings that LOOK the same are not equal when compared. Why is it like this, and how should I do if I want to "check" if the language is a certain one?
if (myLocale.toLanguageTag()=="sv")
{
//Changing language from Swedish to English
}
else
{
Toast.makeText(parent.getContext(),
myLocale.toString(), Toast.LENGTH_SHORT).show();
//Here, the toast will tell me what myLocale.toString is "sv",
//and so is myLocale.toLanguageTag(). Yet they are not equal...
}
As stated in the documentation:
Locale.toString()
returns a string representation of this Locale object, consisting of language, country, variant, script, and extensions, whatever is available, as below:language + "_" + country + "_" + (variant + "_#" | "#") + script + "-" + extensions
Language is always lower case, country is always upper case, script is always title case, and extensions are always lower case.
for exampleen_US
,en
Whereas Locale.toLanguageTag() returns you the same stuff (language, country, and variant), but as a tag. Here Tag
means some code given for language, country and variant defined by some IETF's BCP 47 standard (BCP = 'Best Current Practice').
for example en-US
The only difference I can see is the _
and -
or perhaps some language/country codes too.
In nutshell, both of them return String
; one returns a normal string representation of the Locale whereas the later returns a string as a well-formed IETF BCP 47 language tag representing the locale.
The documentation also suggests using toString
only in debugging mode:
This behavior is designed to support debugging and to be compatible with previous uses of toString that expected language, country, and variant fields only. To represent a Locale as a String for interchange purposes, use toLanguageTag().
Hope it helps.
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