moictab
moictab

Reputation: 959

Autofill EditText in AlertDialog

I have a listView with some items. I am trying to implement an "edit" option for everey item, where the user can change the text of the item's fields through a dialog. The dialog is shown when the user clicks on a button in the item's layout, so the dialog is called through the button.onClickListener(...) inside the adapter of the listView.

My problem is that I want to show the user the current information of the item in the dialog, so I made a bunch of EditText in the view that I want to fill with the current data of the item when the dialog is created, and let the user delete the text in the fields (I mean, editTexts) that he wants to and write new text in them. But, since I am inflating a view in the dialog (new AlertDialog.Builder(getActivity()).setView(view)), the second time the user tries to edit an item, my app crashes because the inflated view in the dialog already has a parent. I don't want to remove the view's parent because I am inflating the view OUTSIDE the button.onClickListener(...) since I want the current data to appear in the creation of the dialog.

How do I do that?

Here you have some code, hope it's enough:

Adapter for my ListView inside my Fragment:

public class ContactosAdapter extends ArrayAdapter<Contacto> {  //This is an inner class inside myFragment

    ...

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ...

        inflater = LayoutInflater.from(context);
        view = inflater.inflate(R.layout.dialog_nuevo_contacto, null);

        ...

        buttonEditar.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                AlertDialog dialog = new AlertDialog.Builder(getActivity()).setView(view).setTitle(R.string.editar_contacto).setPositiveButton(R.string.aceptar, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    ...

                    }

                }).setNegativeButton(R.string.cancelar, null).setCancelable(false).create();
                dialog.show();

            }
       });

Upvotes: 0

Views: 799

Answers (2)

michal.z
michal.z

Reputation: 2075

Inflate your layout for dialog inside buttonEditar.setOnClickListener(new View.OnClickListener() { ... }.

Upvotes: 1

Ankit Kumar
Ankit Kumar

Reputation: 3723

I think this will work.. Try this

    AlertDialog.Builder alert_with_edittext = new AlertDialog.Builder(MyActivity.this);
    LayoutInflater inflater=MyActivity.this.getLayoutInflater();

added the layout to the alert dialog

    View layout=inflater.inflate(R.layout.dialog,null);       
    alert.setView(layout);
    final EditText item_form_list =(EditText)layout.findViewById(R.id.dialog_edittext);

Upvotes: 1

Related Questions