Да / Нет диалога и жизненного цикла - PullRequest
3 голосов
/ 21 июля 2011

Я уверен, что это фундаментальный вопрос, но мои исследования ничего полезного не дают.Мое новое приложение должно использовать диалог Да / Нет при некоторых обстоятельствах, и я не понимаю, как диалоги вписываются в жизненный цикл приложения.Например, я хотел бы создать метод для поддержки этого типа конструкции:

if (yesNoAlert("Title", "Do you want to try again?") == true) {
   action1();
} else {
   action2();
}

Метод будет выглядеть примерно так:

private boolean yesNoAlert(String title, String message) {
    final boolean returnValue;

    DialogInterface.OnClickListener dialogClickListener = new
                       DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which){
            case DialogInterface.BUTTON_POSITIVE:
                returnValue = true;
                break;

            case DialogInterface.BUTTON_NEGATIVE:
                returnValue=false;
                break;
            }
        }
    };

    alertbox = new AlertDialog.Builder(this);
    alertbox.setMessage(message)
            .setTitle(title)
            .setPositiveButton("Yes", dialogClickListener)
            .setNegativeButton("No", dialogClickListener)
            .show();
}

... но как вы можетевидите, это не закончено - есть ряд вещей, которые не совсем правильны.Часть, которую я пропускаю, это как узнать, что диалог закончен ... какой метод существует, который можно использовать, чтобы приложение могло понять, что кнопка была нажата?Конечно, на это реагируют действия BUTTON_POSITIVE и BUTTON_NEGATIVE, но мой вопрос заключается в том, как вернуть с индикатором, чтобы код, ожидающий ответа, снова поднялся в action1 () или action2 ()В зависимости от ответа.

В настоящее время я не вижу ни способа, чтобы мое приложение могло это определить, ни даже действительного способа сделать метод / функцию из этого кода.поэтому я пропускаю какую-то жизненно важную часть жизненного цикла.

Где я мог бы прочитать об этом?Конечно, в интернете есть много информации об этом, но для меня, как относительного новичка, это похоже на попытку пить из пожарного рукава.

Ответы [ 3 ]

2 голосов
/ 21 июля 2011

Это сделает действие, которое необходимо выполнить, динамическим:

private Thread actionToDo;

private void yesNoAlert(String title, String message)
{
    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
    {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                switch (which)
                {
                    case DialogInterface.BUTTON_POSITIVE:
                    actionToDo.start();
                    break;

                    case DialogInterface.BUTTON_NEGATIVE:
                    break;
                }
            }
    };
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(message).setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).setTitle(title).show();
}
1 голос
/ 21 июля 2011

Вы могли бы сделать так

private boolean yesNoAlert(String title, String message) {
    new AlertDialog.Builder(this).setMessage(message)
        .setTitle(title)
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int which) { action1(); }
        })
        .setNegativeButton("No", new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int which) { action2(); }
        })
        .show();
}
0 голосов
/ 06 февраля 2015

вы можете использовать слушателя для достижения этой цели. Как сказано в документации Android:

  1. Определите интерфейс с действиями, которые необходимо поддерживать (onDialogPositiveClick и onDialogNegativeClick).

    открытый класс NoticeDialogFragment extends DialogFragment {

    /* The activity that creates an instance of this dialog fragment must
     * implement this interface in order to receive event callbacks.
     * Each method passes the DialogFragment in case the host needs to query it. */
    public interface NoticeDialogListener {
        public void onDialogPositiveClick(DialogFragment dialog);
        public void onDialogNegativeClick(DialogFragment dialog);
    }
    
    // Use this instance of the interface to deliver action events
    NoticeDialogListener mListener;
    
    // Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Verify that the host activity implements the callback interface
        try {
            // Instantiate the NoticeDialogListener so we can send events to the host
            mListener = (NoticeDialogListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString()
                    + " must implement NoticeDialogListener");
        }
    }
    ...
    

    }

  2. Создайте класс, который отображает диалоговое окно, реализующий ваш интерфейс.

    открытый класс MainActivity расширяет FragmentActivity реализует NoticeDialogFragment.NoticeDialogListener { ...

    public void showNoticeDialog() {
        // Create an instance of the dialog fragment and show it
        DialogFragment dialog = new NoticeDialogFragment();
        dialog.show(getSupportFragmentManager(), "NoticeDialogFragment");
    }
    
    // The dialog fragment receives a reference to this Activity through the
    // Fragment.onAttach() callback, which it uses to call the following methods
    // defined by the NoticeDialogFragment.NoticeDialogListener interface
    @Override
    public void onDialogPositiveClick(DialogFragment dialog) {
        // User touched the dialog's positive button
        ...
    }
    
    @Override
    public void onDialogNegativeClick(DialogFragment dialog) {
        // User touched the dialog's negative button
        ...
    }
    

    }

  3. Сделайте так, чтобы ваш диалог вызывал эти методы в нужный момент (при обнаружении setPositiveButton или setNegativeButton щелчка).

    открытый класс NoticeDialogFragment extends DialogFragment { ...

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Build the dialog and set up the button click handlers
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(R.string.dialog_fire_missiles)
               .setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // Send the positive button event back to the host activity
                       mListener.onDialogPositiveClick(NoticeDialogFragment.this);
                   }
               })
               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // Send the negative button event back to the host activity
                       mListener.onDialogNegativeClick(NoticeDialogFragment.this);
                   }
               });
        return builder.create();
    }
    

    }

Ссылка http://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents

...