将 onClickListener 附加到 ToggleButton
我有一个 ToggleButton,我需要设置简单的点击操作。如何为 ToggleButton 实现简单的单击侦听器?
如果您需要详细信息,请询问。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我有一个 ToggleButton,我需要设置简单的点击操作。如何为 ToggleButton 实现简单的单击侦听器?
如果您需要详细信息,请询问。
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(9)
ToggleButton 扩展了 View,因此您可以简单地使用
ToggleButton extends View, so you can simply use View.setOnClickListener(), like this:
使用 View.setOnClickListener() 并检查按钮状态。
Use
View.setOnClickListener()
and Check state of button.只是添加其他答案中未强调的一点 - 以编程方式绑定点击处理程序对样板代码来说有点繁重。正如文档中提到的,仅在某些情况下才有必要,例如:
如果 ToggleButton 在布局中定义,在那里绑定处理程序方法会更简单、更清晰
然后只需在 Activity Java 中定义处理程序方法即可。
注意该方法可以有任何名称,但签名必须满足以下条件:
public
方法void
View
类型的单个参数(这将是被单击的View
)Just to add a point not emphasised in the other answers - programatically binding a click handler is a bit heavy on the bolierplate code. As mentioned in the docs, it's only necessary in certain scenarios, such as:
If the ToggleButton is defined in the layout, it's far simpler and cleaner to bind a handler method there
Then only the handler method needs to be defined in the Activity Java
Note the method can have any name, but the signature must meet these criteria:
public
methodvoid
View
(this will be theView
which was clicked)要从代码中添加它,您可以执行以下操作:
但是,您也可以在按钮的 XML 中指定您想要与 onClick 操作/事件关联的方法。
To add it from the code, you can do something like:
However, you can also specify in the XML for your button, which method you want to be associated with the onClick action/event.
如果上面的代码不起作用尝试
if above codes don't work try
尝试
方法href="https://developer.android.com/guide/topics/ui/controls/togglebutton.html" rel="nofollow noreferrer">ToggleButton 类
Try
setOnCheckedChangeListener
method of your ToggleButton class