Getting Switch instance inside ActionBar

╄→гoц情女王★ 提交于 2019-12-10 15:04:48

问题


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
}


来源:https://stackoverflow.com/questions/15338471/getting-switch-instance-inside-actionbar

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