title: How to add switch listener in action bar android?
body: <p>I am trying to add a listener to my switch in action bar for that I have read a lot of answers about it on StackOverflow but my app is crashing on below point. </p>
  
  <p>my main menu xml</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"&gt;
  &lt;item
      android:id="@+id/myswitch"
      android:title=""
      app:showAsAction="always"
      app:actionLayout="@layout/switch_layout"/&gt;
  &lt;/menu&gt;
  </code></pre>
  
  <p>my switch layout </p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="match_parent"
  android:orientation="horizontal"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"&gt;
  &lt;android.support.v7.widget.SwitchCompat
      android:id="@+id/switchForActionBar"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="" /&gt;
  &lt;/RelativeLayout&gt;
  </code></pre>
  
  <p>My on create options menu is this </p>
  
  <pre><code>@Override
  public boolean onCreateOptionsMenu(Menu menu) {
  
      getMenuInflater().inflate(R.menu.mainmenu, menu);
      for (int i = 0; i &lt; menu.size(); i++) {
          MenuItem item = menu.getItem(i);
          if (item.getItemId() == R.id.myswitch) {
              View view = MenuItemCompat.getActionView(item);
              if (view != null) {
                   **Switch mainSwitchOnOffSw = (Switch) view.findViewById(R.id.switchForActionBar);**
                //to do add a listener for this switch
              }
          }
      }
  
      return true;
  }
  </code></pre>
  
  <p>On debugging constantly I found that <strong>Switch mainSwitchOnOffSw = (Switch) view.findViewById(R.id.switchForActionBar);</strong> this line results in application crash. I hope my problem is clear now. I want to attach a listener to my action bar switch but I am unable to get an instance to the object of that switch. Above is how most of the answers on StackOverflow have directed to do. Any help on this would be highly appreciated. </p>
  
  <p>Thank you</p>