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

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

问题描述

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

I have a custom dialog and when I try to get the value of an EditText it returns null.

此行返回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;
}


推荐答案

试试这个:

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

你必须告诉在哪个视图中找到id。否则,它将尝试在 setContentView (通常在 onCreate 中声明)的xml布局中查找视图中的id

You have to tell in which view to find the id. Otherwise it will try to find the id in the view from the xml layout inflated by setContentView (usually declared in onCreate)

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

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