我设法将一个Switch放在操作栏中(如在Wi-Fi设置中).
我将以下mainmenu.xml文件放在/ menu文件夹中:
<?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>
Run Code Online (Sandbox Code Playgroud)
之后我覆盖了onCreateOptionsMenu()活动中的方法,如下所示:
@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);
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,我无法理解何时调用此方法.这是问题所在:它似乎onCreateOptionsMenu甚至没有被调用过onResume(),所以NullPointerException抛出了:
@Override
public void onResume()
{
super.onResume();
// Synchronize the switch with service's status
swtService.setChecked(ServiceHelper.isServiceStarted(this, MySystemService.class.getName()));
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?还有另一种方法将View放在操作栏中吗?
编辑
我的目标API是17,我不关心较低的API.:)
这是应用程序的一个镜头,显示了生命周期方法:

谢谢
android switch-statement android-actionbar oncreateoptionsmenu
我使用QIcon (Qt 4.8.1 with MSVC 2008) 面临一些内存泄漏。
这种情况发生在简单的QAction(如菜单项,甚至是由 Qt Designer 自动生成的菜单项)或容器项(如QTreeWidgetItem)中。
例如:
QTreeWidgetItem *newItem = new QTreeWidgetItem();
newItem->setText(0, "Item");
// This causes a memory leak!
newItem->setIcon(0, QIcon("D:\\Dnl\\QtSandBoxApp\\Resources\\dataset2.png"));
treeWidget->addTopLevelItem(newItem);
Run Code Online (Sandbox Code Playgroud)
经过大量调试后,我发现QIcon内部使用QImage,它似乎被正确销毁(参考计数器降至零)。
我可以生成的最简单的示例如下:
#include "stdafx.h"
#include <QtGui/QApplication>
#include <crtdbg.h>
int main(int argc, char *argv[])
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
QApplication a(argc, argv);
//QPixmapCache::setCacheLimit(0);
// MEMORY LEAK!
// Internally uses QImageReader
QImage image("D:\\Dnl\\QtSandBoxApp\\Resources\\dataset2.png");
// NO MEMORY LEAK!
//QImage image(QSize(16, 16), QImage::Format_ARGB32);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?
这是一个非常烦人的问题,因为它阻止了正确的内存泄漏跟踪(即由应用程序引起的,而不是 …