将EditText添加到警示对话框中。

9

我有以下代码创建了一个警告对话框并在其中添加了两个编辑文本,但是一旦运行应用程序,EditText中的值将无法获取,我的应用程序会因为NullPointerException而崩溃:

代码如下:

AlertDialog.Builder alert = new AlertDialog.Builder(this);
        LayoutInflater inflater=this.getLayoutInflater();
        final EditText usernameInput=(EditText)findViewById(R.id.dialogusername);
        final EditText passwordInput=(EditText)findViewById(R.id.dialogpassword);   
        alert.setView(inflater.inflate(R.layout.dialog,null));
        alert.setTitle("Enter Password");
        alert.setMessage("Enter password to remove the app:");
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            //provide user with caution before uninstalling
            //also here should be added a AsyncTask that going to read the password and once its checked the password is correct the app will be removed
            value1=usernameInput.getText().toString();
            value2=passwordInput.getText().toString();
            if(value1.equals(null)&&value2.equals(null))
            {Toast.makeText(context, "Enter username and password", Toast.LENGTH_SHORT).show();}
         }
        });
        });
        alert.show();

你调用了错误的findViewById。请调用alert.findViewByID。 - Yahor10
谢谢Yahor10,但我尝试按照您的方式操作,由于没有名为alert.findViewById()的函数,我一直收到错误提示;我唯一得到的是this.findViewById(),但它也不起作用。无论如何,我在下面发布了我用来解决这个问题的解决方案。 - Husam A. Al-ahmadi
3个回答

25

感谢大家对我的问题的回答,我认为我已经得到了我上面发布的问题的解决方案:

AlertDialog.Builder alert = new AlertDialog.Builder(MyFeedActivity.this);
        LayoutInflater inflater=MyFeedActivity.this.getLayoutInflater();
        //this is what I did to added the layout to the alert dialog
        View layout=inflater.inflate(R.layout.dialog,null);       
        alert.setView(layout);
        final EditText usernameInput=(EditText)layout.findViewById(R.id.dialogusername);
        final EditText passwordInput=(EditText)layout.findViewById(R.id.dialogpassword);

而我认为问题在于我无法在警示对话框内获得EidtText,但通过以上代码进行操作,一切都能正常工作。


14

使用这个:

final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    final EditText input = new EditText(this);
    input.setHint("hint");
    alertDialog.setTitle("title");
    alertDialog.setMessage(message);
    alertDialog.setView(input);

1

试着像这样编辑

final EditText usernameInput=(EditText)this.findViewById(R.id.dialogusername);
final EditText passwordInput=(EditText)this.findViewById(R.id.dialogpassword);

或者

final EditText usernameInput=(EditText)alert.findViewById(R.id.dialogusername);
final EditText passwordInput=(EditText)alert.findViewById(R.id.dialogpassword);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接