I managed to install the switch inside the action bar (as in the Wi-Fi settings).
I put the following mainmenu.xml file in the / menu folder :
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/item1"
android:titleCondensed="Service"
android:title="Service"
android:actionViewClass="android.widget.Switch"
android:showAsAction="always|withText">
</item>
After that, I redefined the method onCreateOptionsMenu()in activity as follows:
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
swtService = (Switch)menu.findItem(R.id.item1).getActionView();
swtService.setOnCheckedChangeListener(this);
return super.onCreateOptionsMenu(menu);
}
Unfortunately, I cannot understand when this method is called. Here's the problem: it onCreateOptionsMenudoesn't seem to be called before onResume(), so a is thrown NullPointerException:
@Override
public void onResume()
{
super.onResume();
swtService.setChecked(ServiceHelper.isServiceStarted(this, MySystemService.class.getName()));
}
Am I missing something? Is there any other way to put a view in the action bar?
EDIT
My target API is 17 and I don't care about the lower ones. :)
Here's a snapshot of the application showing life cycle methods:

thank
source
share