java Android:如何在自定义 AlertDialog 中检索 Edittext.getText()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12799751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:16:30  来源:igfitidea点击:

Android: How do I retrieve Edittext.getText() in custom AlertDialog?

javaandroidlayoutandroid-edittextandroid-alertdialog

提问by Alexander W

The topic explains what i'm after... I can't retrieve the EditText from my custom view in android. All I get is a Nullpointer Exception. :/ I've marked where the problems are in the code with comments. The ID:s are correct and my XML layout is a simple RelativeLayout containing two EditText attributes. Obviously I'm missing something trivial here, but I've now stared at the code for almost 2 hours without solving this, so I thought I'll give SO a try instead.

该主题解释了我的追求...我无法从 android 中的自定义视图中检索 EditText。我得到的只是一个空指针异常。:/ 我已经用注释标记了代码中的问题所在。ID:s 是正确的,我的 XML 布局是一个简单的 RelativeLayout 包含两个 EditText 属性。显然我在这里遗漏了一些微不足道的东西,但是我现在已经盯着代码看了将近 2 个小时没有解决这个问题,所以我想我会尝试一下。

protected void showLoginDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    // Get the layout inflater
    LayoutInflater inflater = this.getLayoutInflater();

    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the dialog layout
    builder.setView(inflater.inflate(R.layout.activity_login, null))
    // Add action buttons
    .setPositiveButton(R.string.login, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {

            /* ERROR HERE! */
            EditText uName, passWord;
            uName = (EditText) findViewById(R.id.login_username);
            passWord = (EditText) findViewById(R.id.login_password);

            Log.i(TAG, uName.getText().toString() + " " + passWord.getText().toString());
            /* STOP */

            if(the_view.getSocketTask().isConnected) {
                the_view.getSocketTask().send_command("LOGIN ");
            } else {
                showToast("Not connected!");
            }
        }
    })
    .setNegativeButton(R.string.cancel,  new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });      
    builder.create().show();
}

EDIT:

编辑:

After suggestions the following code is a working one! Thanks again!

经过建议,以下代码是可行的!再次感谢!

protected void showLoginDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    // Get the layout inflater
    LayoutInflater inflater = this.getLayoutInflater();



    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the dialog layout
    builder.setView(inflater.inflate(R.layout.activity_login, null))
    // Add action buttons
    .setPositiveButton(R.string.login, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            Dialog f = (Dialog) dialog;
            /* ERROR HERE! */
            EditText uName, passWord;
            uName = (EditText) f.findViewById(R.id.login_username);
            passWord = (EditText) f.findViewById(R.id.login_password);

            Log.i(TAG, uName.getText().toString() + " " + passWord.getText().toString());
            /* STOP */

            if(the_view.getSocketTask().isConnected) {
                the_view.getSocketTask().send_command("LOGIN ");
            } else {
                showToast("Not connected!");
            }
        }
    })
    .setNegativeButton(R.string.cancel,  new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });      
    builder.create().show();
}

Thanks in advance! Alex

提前致谢!亚历克斯

回答by Mohamed_AbdAllah

Cast the Dialog as a View:

将对话框转换为视图:

View v_iew=inflater.inflate(R.layout.activity_login, null)) ;
builder.setView(v_iew);

Then replace:

然后替换:

        uName = (EditText) findViewById(R.id.login_username); 
        passWord = (EditText) findViewById(R.id.login_password);

with

        uName = (EditText) v_iew.findViewById(R.id.login_username);
         passWord = (EditText) v_iew.findViewById(R.id.login_password); 

回答by Kevin

(Can't vote so creating new answer: Took me hours to figure this out; adding the qualifier finally fixed it - like you figure out already)

(不能投票,所以创建新答案:花了我几个小时才弄明白这个问题;添加限定符终于解决了 - 就像你已经弄清楚了一样)

Doesnt work: final Dialog dialog = new Dialog(this); ... keyInput = (EditText) findViewById(R.id.key_input);

不起作用:最终对话框对话框 = 新对话框(这个);... keyInput = (EditText) findViewById(R.id.key_input);

Works: final Dialog dialog = new Dialog(this); ... keyInput = (EditText) dialog.findViewById(R.id.key_input);

作品:最终对话框对话框=新对话框(这个);... keyInput = (EditText) dialog.findViewById(R.id.key_input);

回答by Rajat Anantharam

In the case of an EditText you should implement TextWatcherIt is generally a very bad idea to use editText.getText()

在 EditText 的情况下,你应该实现TextWatcher使用 editText.getText() 通常是一个非常糟糕的主意

Here is a very simple example code for Custom Dialog containing an EditText as part of the layout. There is also a button that needs to be on the same layout which when clicked will show you the text which you just entered. Have fun!

这是自定义对话框的一个非常简单的示例代码,其中包含一个 EditText 作为布局的一部分。还有一个按钮需要位于相同的布局上,单击该按钮时会显示您刚刚输入的文本。玩得开心!

        final String inputString = null;
        final Dialog dialog = new Dialog(YourActivityName.this);
        dialog.setContentView(R.layout.custom_dialog_layout);
        EditText editText = (EditText) dialog.findViewById(R.id.id_of_edit_text);
        Button done = (Button) dialog.findViewById(R.id.done);
        dialog.show();
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                inputString = s.toString();

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });

        done.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(YourActivityName.this, inputString, Toast.LENGTH_SHORT);
                dialog.dismiss();

            }
        });