首页 > 解决方案 > 取消单击按钮或视图时如何添加功能?

问题描述

我有多个视图可以单击,但关键是当您单击其中一个时,其他视图无法单击,我尝试了这种方式:

1.创建了一个默认为false的布尔变量(var isButtonClicked = false, or isViewClicked),

2.然后,当我单击按钮(或视图)(在 onClickListener 上)时,我将该变量设为 true,

现在,当我单击一个按钮(或视图)而其他按钮无法单击时,这可以正常工作,但现在的问题是我无法取消单击第一个按钮(视图),这就是我被卡住的时候,我在android中找不到关于unClick的任何信息。

标签: androidkotlinonclicklistener

解决方案


我将您的“取消点击”一词理解为“第二次点击”。

您可以使用可为空的 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。


推荐阅读