如何在Android中通过AlertDialog访问字符串资源

13 浏览
0 Comments

如何在Android中通过AlertDialog访问字符串资源

可能是重复的,底部链接中可能有相同的问题。对于我想要问的具体问题或者为了得到更快的答案,请查看我的问题中的回答。否则,请转到下面的链接。

Android: 如何通过字符串的名称从资源中获取字符串?

===========================================================================

我的问题:

即使可能有重复的问题,我仍然提出了这个问题,但是那些问题对我没有起作用。

我正在尝试访问AlertDialog中的strings.xml,但是我似乎无法做到。我在下面的代码中说了:

.setTitle(@string/AlertTitle)

但是它没有起作用,并且报错了。

有没有可能从AlertDialog中获取字符串,或者这是不可能的?

以下是代码。

这是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  
                           ...
                        }

和strings.xml

Add a New Task
What do you want to do next?
Add
Cancel   

谢谢!

0
0 Comments

问题出现的原因是在Java代码中引用字符串资源时使用了错误的方式。正确的方法是使用R.string.string_name来引用字符串资源。解决方法是将代码改为正确的形式,即使用R.string.string_name来引用字符串资源。具体操作如下:

AlertDialog dialog = new AlertDialog.Builder(this)
                    .setTitle(R.string.AlertTitle) //AlertTitle
                    //...

0
0 Comments

在使用Android中的字符串资源时,应该使用setTitle(getString(R.string.AlertTitle));而不是.setTitle(/AlertTitle);。对于这种特殊情况,有两种设置标题的方法:通过资源ID设置标题,即R.string.AlertTitle,或者通过设置字符串,可以从getString()中获取。在Android: How do I get string from resources using its name?中可以找到更多信息。在ActivityFragment中使用getString而不是getResources().getString(...)。非常感谢您的帮助,我非常感激。

0