'Reference an EditText, that is within an external layout that gets set with .setView of an AlertDialog

The goal is to reference an edittext, that is within an external layout that gets set with .setView. The problem is within its initialization.

This is the code

AlertDialog dSchreiben = new AlertDialog.Builder(this)
    .setTitle("Title")
    .setMessage("Message")
    .setView(getLayoutInflater().inflate(R.layout.layoutwithanEditText, null))
    .setPositiveButton("Positive", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            EditText taskEditText = (EditText) findViewById(R.id.EditTextinLayout);
            //continue
        }
    })
    .setNegativeButton("Abbrechen", null)
    .create();
dSchreiben.show();

As you might have guessed, it throws a null reference exception at EditText taskEditText = (EditText) findViewById(R.id.EditTextinLayout); because I have to put it like EditText taskEditText = (EditText) dSchreiben.findViewById(R.id.EditTextinLayout);.

But in the latter case, it cannot find dSchreiben because it hasn't been created, yet.

If I replace the AlertDialog settings with the explicit object, ie dSchreiben.setTitle("Title"); dSchreiben.setMessage("Message"); etc, it won't work, because the AlertDialog does not inherit a setPositiveButton if being used like that.

How to reference taskEditText within onClick?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source