2016-11-25 108 views
2

它可能會重複作爲底部鏈接。對於我想問的具體問題或獲得更快的答案,請參閱我的問題中的答案。否則,請轉到以下鏈接。如何訪問AlertDialog中的文本android的字符串資源

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

===================================== ========================================================== 我的問題:

我在問這個問題問題,即使有可能重複,但那些沒有爲我工作。

我試圖訪問

的strings.xml

在AlertDialog但我似乎無法做到這一點。我曾經說過

.setTitle(@字符串/ 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中

<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> 

謝謝!

回答

3

當使用字符串資源編程,你應該使用的

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

代替

.setTitle(@string/AlertTitle); 

而且對於這種特殊情況下有兩種方法可以設置標題。無論是低谷資源ID,這將是R.string.AlertTitle或通過設置字符串,它可以從getString()

.setTitle(R.string.AlertTitle); 

看到Android: How do I get string from resources using its name?以獲取更多信息。您可以從ActivityFragment

+0

感謝您的幫助。對此,我真的非常感激。 –

1

使用它時,當你在Java代碼中引用的字符串資源做getString而不是getResources().getString(...),做正確的做法是:R.string.string_name

所以,你的代碼應該像這樣工作:

AlertDialog dialog = new AlertDialog.Builder(this) 
        .setTitle(R.string.AlertTitle) //AlertTitle 
        //... 
相關問題