4

It is possible duplicate as bottom link. For specific question I want to ask or to get a faster answer, see the answer in my question. Otherwise, go to the following link.

Android: How do I get string from resources using its name?

=========================================================================== My question :

I am asking this question even though there are possible duplicates but those didn't worked for me.

I am trying to access to

strings.xml

in AlertDialog but I can't seem to make it. I have said

.setTitle(@string/AlertTitle)

in the following code below but it didn't worked and gave out an error. Is there any possible ways to get strings from AlertDialog or is it impossible?

Code below.

This is AlertMainActivity.java

AlertDialog dialog = new AlertDialog.Builder(this)
                        .setTitle("Add a New Task") //AlertTitle
                        .setMessage("What do you want to do next?") //AlertMessage
                        .setView(taskEditText) 
                        .setPositiveButton("Add", new DialogInterface.OnClickListener() //Add {
                           ...
                        .setNegativeButton("Cancel", null) //Cancel  
                           ...
                        }

and strings.xml

<string name="AlertTitle">Add a New Task</string>
<string name="AlertMessage">What do you want to do next?</string>
<string name="Add">Add</string>
<string name="Cancel">Cancel</string>   

Thanks!

Community
  • 1
  • 1
Ian Sonic
  • 191
  • 1
  • 10

2 Answers2

7

When using String resources programmatically you should use

setTitle(getString(R.string.AlertTitle));

instead of

.setTitle(@string/AlertTitle);

Also for this particular case there are two methods for setting the Title. Either trough the resource id, which would be R.string.AlertTitle or by setting a String, which can get from getString()

.setTitle(R.string.AlertTitle);

see Android: How do I get string from resources using its name? for more information. You can do getString instead of getResources().getString(...) when using it from an Activity or Fragment

Community
  • 1
  • 1
Raymond
  • 2,276
  • 2
  • 20
  • 34
1

When you are referencing string resources in Java code, the correct way to do it is: R.string.string_name.

So your code should work like this:

AlertDialog dialog = new AlertDialog.Builder(this)
                    .setTitle(R.string.AlertTitle) //AlertTitle
                    //...
BMacedo
  • 768
  • 4
  • 10