findviewbyid 在对话框中返回 null

2022-09-01 07:08:58

我有一个自定义对话框,当我尝试获取EditText的值时,它返回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;
}

答案 1

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

dialog.show(),

只有在它之后,我才能使用

dialog.findviewById(R.id.myID).

如果我错过了调用 show(),那么我用 findViewByID 得到一个空值。


答案 2

试试这个:

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

您必须知道在哪个视图中找到id。否则,它将尝试从膨胀的 xml 布局(通常在setContentViewonCreate)


推荐