Java — invoke variables in string.xml

See English answer > Dynamic string using string.xml? 9 for complete code, see my previous question here

If I want to internationalize my application, I need to create string objects for some statements in my project. What bothers me most is this code block

    ...
    else
        Toast.makeText(MainActivity.this, 
            "Good job! The answer was " + comp + ".\n" +
            "You made " + guesses + " guesses.\n" +
            "Restart the app to try again.", 
            Toast.LENGTH_LONG).show();
    }
};

The relevant parts of strings.xml are as follows:

<string name="correct">Good job! The answer was + comp\n
               You made + guesses + guesses.\n
               Restart the app to try again.</string>

I want comp and guess variables to display their respective values, but I don't know how

I plan to do this on the code block

    ...
    else
        Toast.makeText(MainActivity.this, 
            R.string.correct, 
            Toast.LENGTH_LONG).show();
    }
};

thank you.

resolvent:

In your XML file string.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <string name="correct">Good job! The answer was %1$s\n
               You made %2$s guesses.\n
               Restart the app to try again.</string>
</resources>

If you want to add other values to the text, add% 2 $s – >% 3 $s, etc

Then you can use it as in Java:

Toast.makeText(MainActivity.this, getString(R.string.correct, comp, guesses), 
            Toast.LENGTH_LONG).show();

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>