如何使 Java 代码从 XML 文件调用字符串(在 Android Studio 中)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25381703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 07:55:40  来源:igfitidea点击:

How to make the Java code to call a String from a XML file(In Android Studio)

javaandroidxmlstringandroid-studio

提问by App The Android

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 文件中获取它,但是如何?

回答by Héctor

Put getString(R.string.welcome)instead of "WELCOME".

getString(R.string.welcome)代替“欢迎光临”。

回答by nouseforname

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.

可能就足够了。

回答by Itzik Samara

In the res/values folder there is a file called strings.xml put there the String

在 res/values 文件夹中有一个名为 strings.xml 的文件,将字符串放在那里

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 中

Android Multi Language Tutorial

Android 多语言教程

回答by Utkarsh Singh

You can add this line above your current code snippet:

您可以在当前代码片段上方添加此行:

String data=userInput.getEditableText().toString();

Here, userInputis 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();

回答by Tarsbir Singh

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();