android - 取消单击按钮或视图时如何添加功能?
问题描述
我有多个视图可以单击,但关键是当您单击其中一个时,其他视图无法单击,我尝试了这种方式:
1.创建了一个默认为false的布尔变量(var isButtonClicked = false, or isViewClicked),
2.然后,当我单击按钮(或视图)(在 onClickListener 上)时,我将该变量设为 true,
现在,当我单击一个按钮(或视图)而其他按钮无法单击时,这可以正常工作,但现在的问题是我无法取消单击第一个按钮(视图),这就是我被卡住的时候,我在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。
推荐阅读
- java - 为什么 Java 没有 EmptyQueueException?
- webstorm - WebStorm 2018.3 Run/Debug 启动直接报错
- java - 多个类的静态引用
- typescript - Angular 6读取XLS文件并将其保存到变量中
- html - 使用 CSS 实现百分点
- sorting - 数据表 - 包含年龄范围/YADCF 累积过滤器的排序列(使用 columnDefs )
- php - 使用完全限定路径名 (FQPN) 请求文件时是否执行任何类型的搜索
- c - 带有循环的 C 程序中的老虎机
- javascript - 在MYSQL数据库中导出并使字符串有效期为7天
- amazon-s3 - S3 在 CSV 文件上选择 - 如何匹配子字符串