How to use the Strings file inside the code

1

Example strings.xml

<string name="beer">Beer</string>

Example strings (en-us)

<string name="beer">Cerveja</string>

In the code I wanted to reference this:

    @Override
        public void onClick(View v) {
                Toast toast;
                switch (v.getId()){
                    case R.id.ce : toast = Toast.makeText(getApplicationContext(), QUERIA_REFERENCIAR_AQUI ,Toast.LENGTH_SHORT); toast.show(); break;
                    [...]
                    default : break;
                }

So that there is translation in my app even in these messages, because in the layout, it works fine. Thanks!

Would it be possible?

    
asked by anonymous 05.05.2018 / 19:48

1 answer

3

To reference through java use the following flame:

@Override
        public void onClick(View v) {
                Toast toast;
                switch (v.getId()){
                    case R.id.ce : toast = Toast.makeText(getApplicationContext(), getResources().getString(R.string.beer),Toast.LENGTH_SHORT); toast.show(); break;
                    [...]
                    default : break;
            }

Another very easy way is to write the text and then right click on the text and look for the option (I believe the first option) to automatically add to the xml String file and you inform only the name (key), which in this case will be beer.

I hope I have helped!

    
05.05.2018 / 20:04