Violet Giraffe Violet Giraffe - 4 months ago 22
Android Question

AlertDialog.Builder with a custom view: how to initialize the view?

I'm working on an

AlertDialog
for editing a list item. I can pass my editor layout with
Builder.setView
, and I can get the result from the positive button callback, but I don't see a way to initialize the view. E. g. there's an
EditText
that should be displaying a specific string, and so on. Is it doable?

I realize I could subclass
Dialog
, but then it seems I'd need more utility code to achieve the same result. Seems less clean.

Answer

Simply, retain a reference of the view by inflating it beforehand:

LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);

Then, get a reference to your EditText as:

EditText editText = (EditText) dialogView.findViewById(R.id.label_field);