rokkonet

PC・Androidソフトウェア・アプリの開発・使い方に関するメモ

android開発 AlertDialogのボタンオブジェクトの取得

2021 Oct. 30.

出典 Android - android開発 DialogFragmentのonStart()内でのOKボタンのOnClickイベント捕捉|teratail

概要

DialogFragmentのonCreateDialog()内でのAlertDialog.Builderのcreate()時に、「ボタンオブジェクトを取得し、操作する」ハンドラをAlertDialogのOnShowイベントにセットする。

出典ページからのコード

class MyDialogFragment: DialogFragment() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.let {
            val view = requireActivity().layoutInflater.inflate(R.layout.my_dialog, null)
            val builder = AlertDialog.Builder(it).setView(view)
                .setPositiveButton(android.R.string.ok, { dialog, id -> })
                .setNegativeButton(android.R.string.cancel, { dialog, id ->
                    dialog.cancel()
                })

            builder.create().also { dialog ->  // dialogを返すと共にdialogにOnShowListenerをセットする
                dialog.setOnShowListener({
                    val button = dialog.getButton(Dialog.BUTTON_POSITIVE)
                    CODES TO BUTTON
                })
            }
        } ?: throw IllegalStateException("Activity cannot be null")
    }
}