将Switch小部件添加到ActionBar并响应更改事件 [英] Add Switch widget to ActionBar and respond to change event

查看:75
本文介绍了将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="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/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.

推荐答案

您需要致电

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并响应更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆