Add Switch widget to ActionBar and respond to change event

早过忘川 提交于 2019-12-09 04:53:26

问题


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

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.


回答1:


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);
}



回答2:


For those of you using Xamarin. This is the translated version of adneal's answer:

private Switch _actionViewSwitch;

public override bool OnCreateOptionsMenu(IMenu menu)
{
    MenuInflater.Inflate(Resource.Menu.main_activity_actions, menu);

    var menuItem = menu.FindItem(Resource.Id.toggleservice);
    _actionViewSwitch = (Switch) menuItem.ActionView;
    _actionViewSwitch.CheckedChange += ActionViewOnCheckedChange;

    return base.OnCreateOptionsMenu(menu);
}

private void ActionViewOnCheckedChange(object sender, CompoundButton.CheckedChangeEventArgs checkedChangeEventArgs)
{
    // ToDo: stuff that happens when switch gets checked.
}


来源:https://stackoverflow.com/questions/22918812/add-switch-widget-to-actionbar-and-respond-to-change-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!