Setting Textview in java file

48 Views Asked by At

I am making app which use a button and textview. each time user press the button to calculate number, Textview will display a sentence. if A >5 textview will display " good ", if A > 8, textview will display " excellent" and I want words "good" and " excellent" will be shown by many language. In java file where I only put English in: `textView.setText(""); I don't know how to get string data from xml to Java file. Can anyone please help me how to do? below is my code in java file:

button = findViewById(R.id.btn);
textView = findViewById(R.id.textView);
edt1 = findViewById(R.id.edt1);
edt2 = findViewById(R.id.edt2);


button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        a = Float.parseFloat(edt1.getText().toString());
        b = Float.parseFloat(edt2.getText().toString());
        double A = a +b;

     if (Double.compare(A,5f) < 0){
       textView.setText("" );
       
     if (Double.compare(A,8f) > 0){
       textView.setText("" );
        
    }
});
1

There are 1 best solutions below

1
Fede Cana On

To have text strings of different languages you have to set different strings.xml files through the Translation Editor (right click on the strings.xml file -> Open Translation Editor -> Add local -> choose the languages to add). After that you will find different strings.xml files for each language. Enter in each of them the identified name of the string and its translation.

<!-- Inside strings.xml -->
<string name="good">Good</string>
<string name="excellent">Excellent</string>

<!-- Inside strings.xml (it) -->
<string name="good">Buono</string>
<string name="excellent">Eccellente</string>

To get the string resource from xml to java:

getResources().getString(R.string.good)

Now since you are inside View.OnClickListener() you need to do the following:

button = findViewById(R.id.btn);
textView = findViewById(R.id.textView);
edt1 = findViewById(R.id.edt1);
edt2 = findViewById(R.id.edt2);
Context context = this;

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        a = Float.parseFloat(edt1.getText().toString());
        b = Float.parseFloat(edt2.getText().toString());
        double A = a +b;

     if (Double.compare(A,5f) < 0){
       textView.setText(context.getResources().getString(R.string.good));
       
     if (Double.compare(A,8f) > 0){
       textView.setText(context.getResources().getString(R.string.excellent));
        
    }
});