How to use the Strings file inside the code

Asked

Viewed 144 times

1

Hello, inside the Mainactivity XML in Android Studio I can use @string/STRING I would like to know how I would reference a string I have inside the strings.xml in the res folder of Android Studio.

Example strings.xml

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

Example strings(en)

<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, works well. Thank you!

Would it be possible?

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 only enter the name (key), in which case it will be Beer.

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.