Getting Switch instance inside ActionBar

2019-06-22 08:13发布

问题:

I managed to put a Switch inside the action bar (as in the Wi-Fi settings).

I put the following mainmenu.xml file inside 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 overrode the onCreateOptionsMenu() method in the activity, as follows:

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);

    // Get widget's instance
    swtService = (Switch)menu.findItem(R.id.item1).getActionView();
    swtService.setOnCheckedChangeListener(this); 

    return super.onCreateOptionsMenu(menu);
}

Unfortunately, I can't understand when this method is called. Here's the problem: it seems that onCreateOptionsMenu is not called even before onResume(), so a NullPointerException is thrown:

@Override
public void onResume()
{
    super.onResume();

    // Synchronize the switch with service's status
    swtService.setChecked(ServiceHelper.isServiceStarted(this, MySystemService.class.getName()));
}

Am I missing something? Is there another way to put a View inside the action bar?

EDIT

My target API is 17, and I don't care about lower ones. :)

Here's a shot of the application, showing the lifecycle methods called:

Thanks

回答1:

Try this:

    @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
}