Ian Sonic Ian Sonic - 7 days ago 7
Android Question

How to access string resource in android of text in AlertDialog

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!

Answer

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

Comments