Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access string resource in android of text in AlertDialog [duplicate]

Tags:

java

android

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!

like image 945
Ian Sonic Avatar asked Feb 05 '23 15:02

Ian Sonic


1 Answers

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

like image 174
Raymond Avatar answered Feb 08 '23 04:02

Raymond