2011-04-02 126 views
16

我有一个自定义对话框,当我尝试获取EditText的值时,它返回null。findviewbyid在对话框中返回空值

此行返回null

EditText et = (EditText)findViewById(R.id.username_edit); 

这里是将其全部的代码。

protected Dialog onCreateDialog(int id) { 
    switch (id) { 
    case DIALOG_TEXT_ENTRY: 
     LayoutInflater factory = LayoutInflater.from(this); 
     final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null); 
     return new AlertDialog.Builder(TicTacToe.this) 
      //.setIconAttribute(android.R.attr.alertDialogIcon) 
      .setTitle(getTitleText()) 
      .setView(textEntryView) 
      .setPositiveButton("JOIN GAME", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int whichButton) { 
        try 
        { 
         EditText et = (EditText)findViewById(R.id.username_edit); 
          playerName = et.getText().toString(); 
        } 
        catch (Exception e) 
        { 
        } 
       } 
      }) 
      .create(); 
    } 
    return null; 
} 

回答

36

试试这个:

EditText et = (EditText)textEntryView.findViewById(R.id.username_edit); 

你必须知道在哪儿查看找到ID。否则,它会尝试找到从setContentView膨胀的XML布局视图的ID(通常在onCreate申报)

+0

+1伟大的工作人。 – Jacob 2013-03-07 13:01:14

+0

谢谢!为我工作以及 – Urbanleg 2013-06-15 15:10:52

+0

谢谢你保存了一天:) – orchidrudra 2015-04-23 20:38:23

2

我有同样的问题,提出了自己在下面的代码片段:

final Dialog dialog = new Dialog(this); 

dialog.setContentView(R.layout.addbank_dialog); 
dialog.show(); 

Button btnSaveBank = (Button)dialog.findViewById(R.id.btnSaveBank); 

final EditText etBankName = (EditText)dialog.findViewById(R.id.etBankName); 

btnSaveBank.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     try{ 
      String bank = etBankName.getText().toString(); 
      SharedCommonData.dbOps.saveBankInDB(bank); 
     } 
     catch(Exception e){ 
      e.printStackTrace(); 
     } 
     Toast.makeText(SharedCommonData.context, "Bank Saved", Toast.LENGTH_SHORT); 
     refreshBanks(); 
     dialog.dismiss(); 
    } 
}); 

etBankName返回空值,但后来我用dialog.findviewbyid(R.id.etBankName)它工作。

20

在我的情况: 首先,我必须调用

dialog.show(),

,只有经过它,我能够使用

dialog.findviewById (R.id.myID)。

如果我错过了调用show(),比用findViewByID得到了一个null。

+1

这完全违反'AlertDialog.Builder.create()'似乎暗示,也是完全正确的。事实上,即使你不解引用null,只要调用'findViewById',当你最终调用'show()'时会引发不同的异常。谢谢。 – benkc 2015-07-17 21:08:00

+0

这太奇怪了...顺便说一下,设备依赖。在调用Dialog.show()之前,我使用了'Dialog.findViewById()',并且它工作正常。 – Bondax 2016-04-19 13:05:02

6

我遇到过类似的问题。在我的情况下,我有一个自定义布局的对话框,在这个布局有一个radioButton。为了解决这个问题,我使用了以下代码:

View dialogLayout = factory.inflate(R.layout.dialog_layout, null); 
AlertDialog.Builder dialog = new AlertDialog.Builder(context); 
dialog.setView(dialogLayout); 

RadioButton radiobt = (RadioButton) dialogLayout.findViewById(R.id.radioBt);