Getting a Switch Instance Inside an ActionBar

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

    // Get widget instance
    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();

    // Synchronize the switch with service status
    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: Lifecycle methods

thank

+5
source share
1 answer

:

    @Override
    public void onPrepareOptionsMenu(Menu menu){
        super.onPrepareOptionsMenu(menu);
        swtService.setChecked(ServiceHelper.isServiceStarted(this, MySystemService.class.getName()));

    }

@Override
public void onResume()
{
    super.onResume();
    this.getActivity().invalidateOptionsMenu(); // If you are using fragment
    invalidateOptionsMenu(); // If you are using activity
}
+1

All Articles