将EditText添加到警报对话框。

时间:2012-11-27 12:15:54

标签: android android-alertdialog

我有以下代码创建警告对话框,我添加了两个编辑文本但是一旦我运行应用程序,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();

3 个答案:

答案 0 :(得分:22)

感谢各位回答我的问题所做的贡献,我想我已经找到了上面发布的问题的解决方案:

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,但是通过上面的代码完成后,每件事情都适合我。

答案 1 :(得分:11)

使用它:

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);

答案 2 :(得分:1)

尝试像这样编辑

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

OR

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