Nico Müller
Nico Müller

Reputation: 1874

Extending a CustomDialog, edittext always empty

I am trying to add a custom field to IconDialog (https://github.com/maltaisn/icondialoglib)

I added a new EditText into the xml and I am trying to access it in my activity onIconDialogIconsSelected (which is a Callback when the Select button of this dialog is pressed).

The editText.getText() is always empty but I can see it when debugging in the view.

The new class:

public class InputIconDialog extends IconDialog {
    private EditText editText;
    public InputIconDialog() {

    }

    public String getInputText() {
        View v = getLayoutInflater().inflate(R.layout.icd_dialog_icon, null);
        editText = v.findViewById(R.id.icd_edt_InputName); // this editText exists but is always empty
        return editText.getText().toString();
    }
}

Upvotes: 0

Views: 43

Answers (1)

Mostafa Gazar
Mostafa Gazar

Reputation: 2537

The problem here is that you are not actually accessing the view on display. You inflated a new View on a null parent ViewGroup in this line View v = getLayoutInflater().inflate(R.layout.icd_dialog_icon, null);. Although view has been created it is not tied to anything UI wise.

The other problem is that in IconDialog you already set the content of the dialog to the view dialog.setContentView(view); that you inflated there.


A simple solution would be to allow the children of IconDialog to change its base layout.

public class IconDialog extends DialogFragment {

    @LayoutRes
    protected int layoutRes = R.layout.icd_dialog_icon;

    Dialog onCreateDialog(final Bundle state) {
        LayoutInflater inflater = LayoutInflater.from(context);
        @SuppressLint("InflateParams") final View view = inflater.inflate(layoutRes, null);
}

public class InputIconDialog extends IconDialog {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        layoutRes = R.layout.icd_dialog_icon;
    }

A major drawback to such solution is its maintainability long term in the sense that the children of IconDialog need to include all the views it depends on in their layout with <inclue or replication.


Recommendation

I would use onCreateView in IconDialog to set the layout and views and then override it in InputIconDialog and call super. That plus 3 layout files, one for icon_dialog, one for the shared views between the 2 dialogs and one for input_icon_dialog.

Upvotes: 1

Related Questions