5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AlertDialogのボタンタップでダイアログを閉じない方法

Last updated at Posted at 2019-01-08

ダイアログのボタンをタップしたときに、ダイアログを閉じたくない場合があります。
しかしAlertDialog.Builder#setPositiveButtonなどを使用すると、ボタンタップ時に問答無用でダイアログが閉じてしまいます。
これを回避して閉じる/閉じないを制御するには次のような実装をすればよいです。
onResumeでボタンを取得してsetOnClickListenerで振る舞いをオーバーライドしています。

class DummyDialogFragment() : DialogFragment() {
    companion object {
        fun newInstance(): DummyDialogFragment {
            val instance = DummyDialogFragment()
            val args = Bundle()
            instance.arguments = args
            return instance
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val layoutInflater = LayoutInflater.from(requireContext())
        val view = layoutInflater.inflate(R.layout.dialog_layout, null)
        return AlertDialog.Builder(requireContext())
                .setView(view)
                .setPositiveButton(getString(R.string.dialog_button_title_ok), null) // タップ時の振る舞いは`onResume`で設定される
                .create()
    }

    override fun onResume() {
        super.onResume()
        val alertDialog = dialog as AlertDialog
        val positiveButton = alertDialog.getButton(Dialog.BUTTON_POSITIVE)
        // positiveButtonの振る舞いをこのタイミングで実装する
        positiveButton.setOnClickListener {
            val name = (editText?.text?.toString() ?: "").trim()
            if (true) {
                // ダイアログを閉じる
                dismiss()
            } else {
                // ダイアログを閉じずに、エラーを表示するなど
            }
        }
    }
}

参考
https://stackoverflow.com/questions/2620444/how-to-prevent-a-dialog-from-closing-when-a-button-is-clicked

5
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?