在Android对话框中,如果选择了相同的选项,如何不执行任何操作?

huangapple go评论56阅读模式
英文:

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()

huangapple
  • 本文由 发表于 2020年8月3日 19:07:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63228318.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定