英文:
How to do nothing if the same option is selected in an Android dialog?
问题
我有以下对话:
val alertDialog: AlertDialog.Builder = AlertDialog.Builder(context)
val options = arrayOf("红色", "蓝色", "绿色")
alertDialog.setTitle("选择颜色")
alertDialog.setSingleChoiceItems(options, 1) { dialog, position ->
logErrorMessage("位置: " + position)
dialog.dismiss()
}
val alert: AlertDialog = alertDialog.create()
alert.show()
默认选中的值是"蓝色",因为我将1
传递给setSingleChoiceItems
。每当我点击三个选项中的一个时,都会打印出position
。是否有一种方法可以只在选项更改时获取该日志语句?如果保持选定相同的选项,则不想要任何日志语句。谢谢。
英文:
I have the following dialog:
val alertDialog: AlertDialog.Builder = AlertDialog.Builder(context)
val options = arrayOf("Red", "Blue", "Green")
alertDialog.setTitle("Select a color")
alertDialog.setSingleChoiceItems(options, 1) { dialog, position ->
logErrorMessage("position: " + position)
dialog.dismiss()
}
val alert: AlertDialog = alertDialog.create()
alert.show()
The default selected value that is is "Blue", as I pass 1
to setSingleChoiceItems
. Every time I click on one of the three options, I get the position
printed. Is there any way I can get that log statement only if the option is changed? If the same option remains selected, then I want no log statement? Thanks
答案1
得分: 2
假设您不更改默认选择的值,只需进行条件检查,确保位置不等于1
。如果更加动态,请存储当前位置并进行比较:
val alertDialog: AlertDialog.Builder = AlertDialog.Builder(context)
val options = arrayOf("红色", "蓝色", "绿色")
alertDialog.setTitle("选择颜色")
alertDialog.setSingleChoiceItems(options, 1) { dialog, position ->
if(position != 1) {
logErrorMessage("位置: " + position)
}
dialog.dismiss()
}
val alert: AlertDialog = alertDialog.create()
alert.show()
英文:
Assuming you don't change the default selected value, just do a conditional check that the position isn't equal to 1
. If it's more dynamic, then store the current position and compare that instead:
val alertDialog: AlertDialog.Builder = AlertDialog.Builder(context)
val options = arrayOf("Red", "Blue", "Green")
alertDialog.setTitle("Select a color")
alertDialog.setSingleChoiceItems(options, 1) { dialog, position ->
if(position != 1) {
logErrorMessage("position: " + position)
}
dialog.dismiss()
}
val alert: AlertDialog = alertDialog.create()
alert.show()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论