2011-11-29 43 views
1

所以我有一個對話框,意思是接受用戶名和密碼,但是當我嘗試從EditText對象獲得用戶名和密碼時,我似乎無法從資源中獲取EditText對象,我的代碼看起來像喜歡這個。爲什麼我的EditText Resource在我的android應用程序中評估爲null?

protected Dialog onCreateDialog(int ID){ 
    LayoutInflater factory = LayoutInflater.from(this); 
    final View textEntryView = factory.inflate(R.layout.login_dialogue, null); 
    return new AlertDialog.Builder(this) 
     .setTitle("Login:") 
     .setView(textEntryView) 
     .setPositiveButton("login", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int whichButton) { 
       /* Problem occurs below */ 
       View aView = findViewById(R.id.login_dialogue_username); 
       String username = ((EditText) aView).getText().toString(); 
       String password = ((TextView) findViewById(R.id.login_dialogue_password)).getText().toString(); 
       boolean success = attemptLogin(username, password); 
      } 
     }) 
     .setNegativeButton("cancel", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int whichButton) { 

       /* User clicked cancel so do some stuff */ 
      } 
     }) 
     .create(); 
} 

所以,當我在調試步,該aView變量爲空,但我不明白爲什麼。資源位於我的R文件中,它在eclipse中呈藍色,表示它與R文件的名稱匹配。有人知道這裏發生了什麼嗎?

回答

5

您正在查看活動的佈局。嘗試使用

textEntryView.findViewById(R.id.login_dialogue_username); 

改爲。

+0

這解決了我的問題,謝謝!所以'findViwById()'實際上是在對話框下運行的Activity上調用的,所以它沒有看到正確的位置? – wbarksdale

+0

正確,並且您希望在對話框中查找視圖,因此您可以使用虛擬的「View」作爲對話框佈局。 – Craigy

2

我要去無路可退,並假設你EditText感興趣的(R.id.login_dialogue_username)是R.layout.login_dialogue充氣佈局層次,而不是整體活動的內容視圖中。

如果是這樣,您需要使用textEntryView.findViewById(R.id.login_dialogue_username)來查找您正在查找的視圖。

0

您是否嘗試清理並重新編譯您的項目?

它有時發生在我身上,似乎在某些情況下,Android會在R類中用IDs搞砸。清理和重新編譯您的項目將重新生成R類。

相關問題