0

My Action bar items were working fine until I added a menu drawer, now when the activity is first displayed, the switch button on the menu doesn't work and as soon as the drawer opens it starts working absolutely fine. Although I have not called it in my onDrawerOpened method.

// ----------For Options Menu-------------------
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    try { 
    super.onCreateOptionsMenu(menu);
    menu.clear();
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main_screen_menu, menu);

    menuitem1 = menu.findItem(R.id.menu_item1);
    menuitem2 = menu.findItem(R.id.menu_item2);


        final Switch getView = (Switch) menuitem2.getActionView();
        getView.setChecked(false);

        getView.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton arg0,
                    boolean isSelected) {
                if (isSelected) {
                    method1();
                } else {
                    method2();
                }
            }
        });
    } catch (Exception e) {

        e.printStackTrace();
        Log.e("OnCreateOptionsMenu", "exception", e);
    }

    mOptionsMenu = menu;
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    // toggle nav drawer on selecting action bar app icon/title
    if (mDrawerToggle.onOptionsItemSelected(item)) {

        return true;
    }
        // Handle action bar actions click
        switch (item.getItemId()) {
        case R.id.menu_item1: {

            return true;

        }
        case R.id.menu_item2: {

            return true;

        }
        default:
            return super.onOptionsItemSelected(item);
        }

}

Once I open and close the Drawer than the switch is working perfectly! Can anyone please help? Thanks in advance.

Unaiza Khalid
  • 330
  • 2
  • 4
  • 13

1 Answers1

1

You're supposed to call super.onCreateOptionsMenu(menu) after having inflated the menu (as shown in the docs : http://developer.android.com/guide/topics/ui/actionbar.html)

I would change your code to :

// ----------For Options Menu-------------------
    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    try { 
    menu.clear();
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main_screen_menu, menu);

    (...)

    return super.onCreateOptionsMenu(menu);
}

(Not totally sure that it could fix your issue, but it's worth the try)

Orabîg
  • 11,718
  • 6
  • 38
  • 58