我有一个类,并尝试在Actionbar中为一个开关做一个监听器。
我在这里尝试过:Link
在我的content_main.xml中,我这样说:
<android.support.v7.widget.SwitchCompat
android:id="@+id/switchForActionBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Auto refresh" />
然后我试着在这里给动作栏充气:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
final MenuItem toggleservice = menu.findItem(R.id.switchForActionBar);
Switch actionView=(Switch) MenuItemCompat.getActionView(toggleservice );
actionView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked == true){
Intent intentStartSearch = new Intent(getApplicationContext(), SearchBeacon.class);
startActivityForResult(intentStartSearch, REQUEST_ID_MonitoringActivity);
}
}
});
return true;
}
但是我得到了这个错误:
01-13 18:02:34.597 4453-4453/com.patientfinder E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.patientfinder, PID: 4453
java.lang.NullPointerException: Attempt to invoke interface method 'android.view.View android.view.MenuItem.getActionView()' on a null object reference
at android.support.v4.view.MenuItemCompatHoneycomb.getActionView(MenuItemCompatHoneycomb.java:39)
at android.support.v4.view.MenuItemCompat$HoneycombMenuVersionImpl.getActionView(MenuItemCompat.java:176)
at android.support.v4.view.MenuItemCompat.getActionView(MenuItemCompat.java:325)
at com.patientfinder.MainActivity.onCreateOptionsMenu(MainActivity.java:98)
at android.app.Activity.onCreatePanelMenu(Activity.java:2852)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:298)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:85)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:241)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:85)
at android.support.v7.app.ToolbarActionBar.populateOptionsMenu(ToolbarActionBar.java:443)
at android.support.v7.app.ToolbarActionBar$1.run(ToolbarActionBar.java:60)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
为什么我会这样?我试了很久但没有找到解决方案。也许这是因为我在Android开发中是一个全新的......