LoginSignup
5
6

More than 5 years have passed since last update.

Flow & Mortar で AlertDialog を出す

Last updated at Posted at 2015-07-06

Flow と Mortar で Screen を作っていく時、ダイアログを出したい時、以下のような特別なクラスを使って AlertDialog を出します。

Popup で AlertDialog を管理する

Popup<I, R> が AlertDialog を保持し、表示を行います。

ジェネリクスの1番目のパラメータは、AlertDialog に表示する内容を保持する Entity のような型を、2番目のパラメータは AlertDialog での選択結果を表す Entity のような型を指定します。

AlertDialog の選択結果を返すときは、showメソッドにわたってくるPopupPresenter#onDismissed(R)を呼び出します。この時、AlertDialog の各ボタンのイベントコールバック内で、フィールドに保持している AlertDialog のインスタンスを null クリアします。これによって、表示しているかどうかを管理できます。


public class AlertPopup implements Popup<InfoEntity, Result> {
  private final Context mContext;
  private AlertDialog mDialog;

  public AlertPopup(Context context) {
    mContext = context;
  }

  @Override
  public void show(InfoEntity info, boolean withFlourish, PopupPresenter<InfoEntity, Result> presenter) {
    if (mDialog != null) {
      throw new IllegalStateException("Already showing, can't show " + info);
    }

    mDialog = new AlertDialog.Builder(mContext, R.style.Theme_Popup)
        .setView(contentView)
        .setCancelable(true)
        .setPositiveButton(android.R.string.ok, (dialog, which) -> {
          mDialog = null;
          presenter.onDismissed(Result.OK);
        })
        .setNegativeButton(android.R.string.cancel, (dialog, which) -> {
          mDialog = null;
          presenter.onDismissed(Result.CANCEL);
        })
        .setOnCancelListener(d -> {
          mDialog = null;
          presenter.onDismissed(Result.CANCEL);
        }).show();
  }

  @Override
  public boolean isShowing() {
    return mDialog != null;
  }

  @Override
  public void dismiss(boolean withFlourish) {
    mDialog.dismiss();
    mDialog = null;
  }

  @Override
  public Context getContext() {
    return mContext;
  }
}

public enum Result {
  OK, CANCEL
}

PopupPresenter で表示と結果の受け取りをハンドルする

Popup専用にPopupPresenterというPresenterが用意されています。
自分たちで実装する部分は、結果を受け取ってどうするのか、という部分だけです。


public class PopupScreen extends Path {
  public static class PopupPresenter extends mortar.PopupPresenter<InfoEntity, Result> {
    @Inject
    public PopupPresenter() {}

    @Override
    protected void onPopupResult(Result result) {
      // TODO implement your own code here
    }
  }
}

最終的に、この PopupPresenter 経由でダイアログを表示することになります。


public class PopupView extends FrameLayout {
  @Inject
  PopupScreen.PopupPresenter mPresenter;

  @Override
  protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    Button button = (Button) findViewById(R.id.button);
    InfoEntity e = InfoEntity.create(); // AlertDialog に出す情報を持つ
    button.setOnClickListener(v -> mPresenter.show(e));
  }
}
5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6