在做一个AlertDialog的点击事件设置的时候:
AlertDialog.Builder(this).apply { var numberIndex = 0 setTitle("choose one") setSingleChoiceItems(choice, 0) { _, which -> numberIndex = which} setPositiveButton("OK") { dialog, _ -> setCheatResult(true, choice[numberIndex].toInt())//把下一个数字设为自己想要的 binding.nextNumberText.text = choice[numberIndex] dialog.dismiss() } setNegativeButton("Cancle") { dialog, _ -> setCheatResult(false, nextNumber) dialog.dismiss() } show() }
不是很明白接口:
void onClick(DialogInterface dialog, int which)
中的which是什么意思,我一开始以为是在列出来的选项中选择其中一个,然后在setPositiviButton中的which就是选择好的item的下标。后来发现setSing里面的which和setPositivi里的which是不一样的。
setPositive里面的下标永远是-1,搞得我一开始老是数组越界,后来才知道在setSingle里面把下标存好才行。
原文:https://www.cnblogs.com/--here--gold--you--want/p/14768912.html