How to get menu item id on action bar when other menu item clicked

Adyana Permatasari picture Adyana Permatasari · Aug 18, 2013 · Viewed 24.6k times · Source

So I have menu items on action bar. on onOptionsItemSelected, I want to change the menu items images.

Here's my code

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
    case R.id.todaySched:{
        viewTodaySched();
        item.setIcon(R.drawable.calendarselected);
        infoLog=(MenuItem)findViewById(R.id.infoLog);
        infoLog.setIcon(R.drawable.book);

        return true;}
    case R.id.infoLog:{
        viewInfoLog();
        item.setIcon(R.drawable.bookselected);
                    todaySched=(MenuItem)findViewById(R.id.todaySched);
        todaySched.setIcon(R.drawable.calenderselected);
        return true;}
    default:
        return super.onOptionsItemSelected(item);
    }
}

But the icon won't change when I clicked it, and I got run time error. e.g: When I click todaySched icon, It seems like I can't get the infoLog item id.

My LogCat: LogCat

Answer

Mohit picture Mohit · Aug 18, 2013

As per you logcat, you getting class cast exception and you have used sharlockactionbar. so try and check if you have imported the correct MenuItem and Menu which should like this:

import com.actionbarsherlock.view.MenuItem;
and
import com.actionbarsherlock.view.Menu; 

instead of

import android.view.MenuItem;
and
import android.view.Menu;

Edit:

Here is how you can change both icons on just a single click:

  private Menu menu;
private MenuItem item1, item2;
Boolean original = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getSupportMenuInflater().inflate(R.menu.menu, menu);

    this.menu = menu;
    return true;

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.todaySched) {
        update();

    } else if (id == R.id.infoLog) {

        update();
    }

    return true;

}

private void update() {

    item1 = menu.findItem(R.id.todaySched);
    item2 = menu.findItem(R.id.infoLog);

    if (original) {
        item1.setIcon(getResources().getDrawable(
                android.R.drawable.ic_menu_search));
        item2.setIcon(getResources().getDrawable(
                android.R.drawable.ic_menu_report_image));
        original = false;
    } else if (!original) {

        item1.setIcon(getResources().getDrawable(
                android.R.drawable.ic_menu_my_calendar));
        item2.setIcon(getResources().getDrawable(
                android.R.drawable.ic_menu_info_details));
        original = true;
    }

}

checked and is working. Now use it as per your requirement..

Cheers....