我已经搜索了数小时,希望找到解决方案。我只想在ActionBar下添加一个开关(就像在蓝牙设置中一样)。我在这里找到了一个类似的问题,但它可能已经过时了。无论如何,这是我的代码:
MainActivity:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.myswitch);
switchButton = (Switch) item.getActionView();
return super.onCreateOptionsMenu(menu);
}
menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<item
android:id="@+id/menu_switch"
android:title="off/on"
app:showAsAction="always"
app:actionLayout="@layout/switchlayout"
app:actionViewClass="android.support.v7.widget.Switch" />
</menu>
switchlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Switch
android:id="@+id/myswitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="#1E88E5" />
</RelativeLayout>
但是无论我做什么都会得到以下错误信息:
尝试在空对象引用上调用... getActionView()'
我很困惑,因为在定义 R.id.myswitch
的前一行,我刚刚定义了项目(item),我弄错了吗?
MenuItemCompat.getActionView
。该链接建议使用searchItem.getActionView();
。 - Shivam Pokhriyal