简体   繁体   中英

Disable ActionBar button dynamically

I want to disable the "attachment" button when there is no attachment is the page user loads. I searched every stack overflow suggestion but I think I'm getting something wrong. What I did is:

  • set a boolean to find if there are attachments.
  • call invalidateOptionsMenu();
  • try to disable the action bar button

     @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.inpostmenu, menu); return super.onCreateOptionsMenu(menu); if (attachments) { menu.findItem(R.id.attach).setEnabled(!attachments); } } 

I get an Unreachable Statement error on

menu.findItem(R.id.attach).setEnabled(!attachments);

What is wrong with my code?

The Unreachable Statement is because you're trying to do stuff after the function already returned. That code can never be reached. Try:

menu.findItem(R.id.attach).setEnabled(attachments);
return super.onCreateOptionsMenu(menu);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM