android - Add toggle button to the menu to stop and start service -
i trying enable user stops , starts service implementing menu text changed when clicks want add togglebutton
option in menu tool nothing being display in case now. how can fix it?
androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <togglebutton android:id="@+id/toggle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textoff="off" android:texton="on" /> </menu>
mainactivity:
public class mainactivity extends actionbaractivity { togglebutton tbutton; @override public boolean oncreateoptionsmenu(menu menu) { menuinflater inflater = getmenuinflater(); inflater.inflate(r.menu.main_menu, menu); return true; } @override public boolean onoptionsitemselected(menuitem item) { switch (item.getitemid()) { case r.id.toggle: tbutton = (togglebutton) findviewbyid(r.id.toggle); tbutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { if (((togglebutton) v).ischecked()) { intent = new intent(mainactivity.this, trackingservice.class); startservice(i); system.out.println("test checked, start service"); } else { // stop service when menu button clicks. intent = new intent(mainactivity.this, trackingservice.class); stopservice(i); system.out.println("test not checked, stop service"); } } }); return true; default: return false; } } }
edit:
@override public boolean onoptionsitemselected(menuitem item) { switch (item.getitemid()) { case r.id.checkable_menu: if (ischecked = !item.ischecked()) { item.setchecked(ischecked); intent = new intent(this, trackingservice.class); startservice(i); system.out.println("test if onoptionsitemselected"); } else { intent = new intent(this, trackingservice.class); stopservice(i); system.out.println("test else onoptionsitemselected"); } return true; default: system.out .println("test default onoptionsitemselected invoked."); return false; } }
as mentioned above, can't add toggle button menu. can use android:checkable
property in menu item handle 2 states.
something like:
menu:
<item android:id="@+id/checkable_menu" android:checkable="true" android:title="@string/checkable" />
activity:
private boolean ischecked = false; @override public boolean onprepareoptionsmenu(menu menu) { menuitem checkable = menu.finditem(r.id.checkable_menu); checkable.setchecked(ischecked); return true; } @override public boolean onoptionsitemselected(menuitem item) { switch (item.getitemid()) { case r.id.checkable_menu: ischecked = !item.ischecked(); item.setchecked(ischecked); return true; default: return false; } }
ps: copied code here.
or can update item icon on click event show 2 states item.seticon(yourdrawable));
Comments
Post a Comment