rokkonet

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

android開発 AlertDialog setPositiveButton(), setNeutralButton(), setNegativeButton()の第2引数はダイアログへのクリックのリスナ

2022 Feb. 13

参考ページ
KotlinでAlertDialogを作るときの「which->」ってどういう... - Yahoo!知恵袋
DialogInterface.OnClickListener  |  Android Developers


AlertDialog.Builder(activity).setView(myDialogView).setTitle("My Title")
    .setPositiveButton("OK") { dialog, which -> // OKボタン押下時の処理 }


上記の例は、次のコードをラムダ式で表現したもの。

AlertDialog.Builder(activity).setView(myDialogView).setTitle("My Title")
    .setPositiveButton("OK",
        DialogInterface.OnClickListener() {
            public onClick(dialog: DialogInterface , which: Int) {
                // OKボタン押下時の処理
            }
        }
    )

上記コードで
dialogはDialogInterface: the dialog that received the click
(dialogはクリックされたダイアログ)
whichはint: the button that was clicked (ex. DialogInterface#BUTTON_POSITIVE) or the position of the item clicked
(whichはクリックされたボタン、もしくは、ダイアログ内で押されたアイテムのpositionを表す)

AlertDialog setPositiveButton(), setNeutralButton(), setNegativeButton()の第2引数にはDialogInterface.OnClickListener()を記述する