[英]How to make the Java code to call a String from a XML file(In Android Studio)
I have this code and I will like to make it multi language app. 我有这个代码,我想使它成为多语言应用程序。 What I want is to use the Strings from the Strings.xml file under the directory of values.
我想要的是使用值目录下的Strings.xml文件中的字符串。
Let's say I have a Toast
... 假设我有一个
Toast
......
Toast.makeText(getApplicationContext(), "WELCOME", Toast.LENGTH_LONG).show();
But I don't want to put the welcome in the java but to get it from the xml file, but How? 但是我不想把欢迎放在java中但是要从xml文件中获取它,但是如何?
把getString(R.string.welcome)
改为“WELCOME”。
You have to use it like this: 你必须像这样使用它:
getApplicationContext().getResources().getString(R.string.YOURSTRING);
Depending where in code, a simple 取决于代码中的位置,简单
getString(R.string,ID);
could be enough. 可能就够了。
In the res/values folder there is a file called strings.xml put there the String 在res / values文件夹中有一个名为strings.xml的文件,其中包含String
Example 例
<string name="welcome">Welcome</string>
and change the Toast to 并将Toast改为
Toast.makeText(getApplicationContext(),R.string.welcome, Toast.LENGTH_LONG).show();
now if you want to add more languages create libraries in the res folder named according to the language : values-fr/ and place inside strings.xml 现在,如果要添加更多语言,请在根据语言命名的res文件夹中创建库: values-fr /并放在strings.xml中
You can add this line above your current code snippet: 您可以在当前代码段上方添加此行:
String data=userInput.getEditableText().toString();
Here, userInput
is the id of your EditText tag in xml file. 这里,
userInput
是xml文件中EditText标记的id。
And just change the original line of your code to: 只需将代码的原始行更改为:
Toast.makeText(getApplicationContext(), "You entered "+data, Toast.LENGTH_LONG).show();
String file 字符串文件
<string name="hi"> Hi </string>
<string name="ten"> out of 10 </string>
<string name="youHaveScored"> you have Scored </string>
Java file Java文件
String finalScore = getString(R.string.hi) +name+ getString(R.string.youHaveScored)+score+ getString(R.string.ten);
Toast.makeText(getApplicationContext(),finalScore,Toast.LENGTH_LONG).show();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.