获取里面的ActionBar交换机实例 [英] Getting Switch instance inside ActionBar
问题描述
我设法把操作栏里面的开关(如Wi-Fi设置)。
I managed to put a Switch inside the action bar (as in the Wi-Fi settings).
我把下面的 mainmenu.xml 的/菜单文件夹中的文件:
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>
在我推翻活动中的 onCreateOptionsMenu()
方法,如下所示:
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);
}
不幸的是,我无法理解时,该方法被调用。
这里的问题:它似乎 onCreateOptionsMenu
之前 onResume()
,所以 NullPointerException异常
被抛出:
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?
修改
我的目标API是17,我不关心较低的。 :)
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:
感谢
推荐答案
试试这个:
@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
}
这篇关于获取里面的ActionBar交换机实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!