我有多个视图可以点击,但重点是当你点击其中一个视图时,其他的视图就不能点击了,我试过这种方法。
1.创建一个布尔变量,默认为false ( var isButtonClicked = false,或isViewClicked )。
2.然后当我点击按钮(或视图)时(onClickListener ),我让这个变量为真。
现在当我点击一个按钮(或视图),其他的按钮不能点击时,这很好用,但现在的问题是,我不能取消点击第一个按钮(视图),这时我就卡住了,我在android中找不到任何关于unClick的东西。
我把你说的 "取消点击 "理解为 "点击了第二次"。
与其使用布尔变量,你可以使用一个可空的View引用,有点像这样。
private var clickedButton: View? = null
lateinit val buttons: List<Button> // put the buttons in a list and assign to this in onCreate
// Set this listener on each button.
val buttonListener = OnClickListener { view ->
when (view) {
clickedButton -> {
clickedButton = null
// other things you want to do when toggling the button off
}
null -> {
clickedButton = view
// other things you want to do when toggling a button on
}
else -> {} // Do nothing. Some other button is toggled on.
}
}
但可能最好是禁用所有没有打开的按钮 这样它们在视觉上看起来就像你不能按它们一样了 在这种情况下,你的监听器应该主动设置所有按钮的启用状态。就像这样。
private var isAButtonPressed = false
lateinit val buttons: List<Button> // put the buttons in a list and assign to this in onCreate
// Set this listener on each button.
val buttonListener = OnClickListener { view ->
if (isAButtonPressed) {
buttons.forEach { it.enabled = true }
// other things you want to do when toggling a button off
} else {
buttons.forEach { it.enabled = it == view }
// other things you want to do when toggling a button on
}
isAButtonPressed = !isAButtonPressed
}
你也可以考虑使用ToggleButton,它有选中和不选中的状态。