How to force Java code to call String from an XML file (in Android Studio)

I have this code and I want to make it a multilingual application. I want to use the lines from the Strings.xml file in the values ​​directory.

Say I have a Toast ...

 Toast.makeText(getApplicationContext(), "WELCOME", Toast.LENGTH_LONG).show(); 

But I do not want to put a greeting in java, but to get it from an XML file, but How?

+6
source share
4 answers

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

+8
source

You should use it as follows:

 getApplicationContext().getResources().getString(R.string.YOURSTRING); 

Depending on the code, simple

 getString(R.string,ID); 

may be enough.

+5
source

In the res / values ​​folder there is a strings.xml file that puts String

Example

 <string name="welcome">Welcome</string> 

and change Toast to

 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 put inside strings.xml

Android Multi Language Tutorial

+2
source

You can add this line above your current code snippet:

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

Here userInput is the identifier of the EditText tag in the XML file.

And just change the source line of your code to:

 Toast.makeText(getApplicationContext(), "You entered "+data, Toast.LENGTH_LONG).show(); 
0
source

Source: https://habr.com/ru/post/974020/


All Articles