Android AlertDialog запоминает строку из предыдущего показанного? - PullRequest
0 голосов
/ 21 ноября 2011

Проблема, с которой я сталкиваюсь в своем диалоговом окне Alert, заключается в том, что у меня есть пользовательский диалог, в котором есть 3 вида текста edittext end 3 когда я выбираю контакт из контактов, я просто заполняю информацию в редактируемом тексте dilaog, например contactName.setText (bla); однако здесь происходит странная вещь, что если я отменяю диалог и снова выбираю другой контакт, данные в диалоговом окне не изменяются и запоминают детали из первого выбранного контакта? Int странно? кажется, что, как только он создает диалог, даже если я вызываю тот же процесс, создавая диалог снова, он сохраняет первый диалог и продолжает показывать тот же диалог. Есть ли кто-нибудь, кто имел такой же опыт и знает, как это решить?

Вот код, который обрабатывает результат, возвращаемый из средства выбора контактов.

 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         if (resultCode == RESULT_OK) {
                switch (requestCode) {
                case CONTACT_PICKER_RESULT:
                    Cursor cursor = null;
                    String email = "";
                    try {
                        Uri result = data.getData();
                        Log.v(DEBUG_TAG, "Got a contact result: "
                                + result.toString());

                        // get the contact id from the Uri
                        String id = result.getLastPathSegment();

                        // query for everything email
                        cursor = getContentResolver().query(Email.CONTENT_URI,
                                null, Email.CONTACT_ID + "=?", new String[] { id },
                                null);

                        int emailIdx = cursor.getColumnIndex(Email.DATA);

                        // let's just get the first email
                        if (cursor.moveToFirst()) {

                            email = cursor.getString(emailIdx);
                            contactUEmail=email;
                            Log.v(DEBUG_TAG, "Got email: " + email);
                        } else {
                            Log.w(DEBUG_TAG, "No results");
                        }
                    } catch (Exception e) {
                        Log.e(DEBUG_TAG, "Failed to get email data", e);
                    } finally {
                        if (cursor != null) {
                            cursor.close();
                        }
                      //  EditText emailEntry = (EditText) findViewById(R.id.invite_email);
                      //  emailEntry.setText(email);
                        if (email.length() == 0) {
                            Toast.makeText(this, "No email found for contact.",
                                    Toast.LENGTH_LONG).show();
                        }

                    }

                    showDialog(DIALOG_ADD_NEW_CALL);// this is where I call the dialog.
                    break;
                }

            } else {
                Log.w(DEBUG_TAG, "Warning: activity result not ok");
            }
        }

и вот диалоговое окно DIALOG_ADD_NEW_CALL;

case DIALOG_ADD_NEW_CALL:
        {
        builder = new AlertDialog.Builder(this);
        entryView = getLayoutInflater().inflate(R.layout.entry, null);
        builder.setView(entryView);
        CNameEditor = (EditText) entryView.findViewById(R.id.cName);
        CEmailEditor = (EditText) entryView.findViewById(R.id.cEmail);
        CPhoneEditor = (EditText) entryView.findViewById(R.id.cPhone);

        if(!contactUEmail.equals(""))//here is the code that I am setting the text.
        CEmailEditor.setText(contactUEmail);
        else{}

        builder.setTitle(R.string.addDialogTitle);
        builder.setPositiveButton(R.string.addItem,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }   
                });

        builder.setNegativeButton(R.string.cancelItem,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.cancel();

                    }
                }).create();

        return builder.create();

        }

Ответы [ 2 ]

1 голос
/ 21 ноября 2011

Чтобы уничтожить диалог, вы можете позвонить removeDialog.Кроме того, вы можете переопределить onPrepareDialog и обновить диалоговое окно, прежде чем оно отобразится.Только к вашему сведению, оба метода устарели в пользу DialogFragment вместе с FragmentManager, но вам, вероятно, придется переделать много кода, чтобы использовать их.

0 голосов
/ 21 ноября 2011

Переопределить onPrepareDialog

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
    switch (id) {
    case DIALOG_ADD_NEW_CALL:
        AlertDialog callDialog = (AlertDialog) dialog;
        View entryView = callDialog;
        CNameEditor = (EditText) entryView.findViewById(R.id.cName);
        CEmailEditor = (EditText) entryView.findViewById(R.id.cEmail);
        CPhoneEditor = (EditText) entryView.findViewById(R.id.cPhone);
        // do stuff to those variables here
    }
}
...