findviewbyid 在对话框中返回 null [英] findviewbyid returns null in a dialog

查看:54
本文介绍了findviewbyid 在对话框中返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a custom dialog and when I try to get the value of an EditText it returns 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;
}

推荐答案

就我而言:首先我必须调用

In my case: First I must call the

dialog.show(),

dialog.show(),

只有在它之后我才能使用

and only after it I was able to use

dialog.findviewById(R.id.myID).

dialog.findviewById(R.id.myID).

如果我错过了调用 show(),那么 findViewByID 会返回一个空值.

If I missed to call the show(), than I got a null back with findViewByID.

这篇关于findviewbyid 在对话框中返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆