将Switch小部件添加到ActionBar并响应更改事件

编程入门 行业动态 更新时间:2024-10-14 10:42:16
本文介绍了将Switch小部件添加到ActionBar并响应更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我能知道如何在ActionBar中添加Switch小部件并处理click事件或切换更改事件.

Can I know how to add Switch widget in ActionBar and handle the click event or toggle change event.

目前,我可以在ActionBar中为Switch充气,但无法响应更改事件.我已经在下面添加到main.xml中.

For now I can inflate the Switch in ActionBar but unable to respond to change event. I have added below to main.xml.

<menu xmlns:android="schemas.android/apk/res/android" xmlns:tools="schemas.android/tools" tools:context="com.example.MainActivity" > <item android:id="@+id/toggleservice" android:actionViewClass="android.widget.Switch" android:showAsAction="ifRoom" android:title="@string/toggle_service"/> </menu>

我想在用户单击开关并更改其状态时启动服务.任何帮助都将受到高度赞赏.

I want to start a service when user clicks on switch and change it's state. Any help is highly appreciated.

推荐答案

您需要致电 MenuItem.getActionView ,这是一个示例:

You need to call MenuItem.getActionView, here's an example:

@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate your Menu getMenuInflater().inflate(R.menu.your_menu, menu); // Get the action view used in your toggleservice item final MenuItem toggleservice = menu.findItem(R.id.toggleservice); final Switch actionView = (Switch) toggleservice.getActionView(); actionView.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // Start or stop your Service } }); return super.onCreateOptionsMenu(menu); }

更多推荐

将Switch小部件添加到ActionBar并响应更改事件

本文发布于:2023-11-22 14:32:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617821.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:部件   事件   Switch   ActionBar

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!