Saturday, February 22, 2014

Show/Hide Menu Item dynamically

This example demonstrate how to show/hide menu items dynamically using Java code, by calling setVisible() method. Even if a menu item is not visible, it may still be invoked via its shortcut. To completely disable an item, set it to invisible and disabled.

Show/Hide Menu Item dynamically
Show/Hide Menu Item dynamically

MainActivity.java
package com.example.androiddynamicmenu;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ToggleButton;

public class MainActivity extends Activity {
 
 ToggleButton btn1, btn2, btn3;
 Menu myMenu;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  btn1 = (ToggleButton)findViewById(R.id.option1);
  btn2 = (ToggleButton)findViewById(R.id.option2);
  btn3 = (ToggleButton)findViewById(R.id.option3);
  
  btn1.setOnCheckedChangeListener(btnOnCheckedChangeListener);
  btn2.setOnCheckedChangeListener(btnOnCheckedChangeListener);
  btn3.setOnCheckedChangeListener(btnOnCheckedChangeListener);
 }
 
 OnCheckedChangeListener btnOnCheckedChangeListener =
  new OnCheckedChangeListener(){

   @Override
   public void onCheckedChanged(CompoundButton buttonView, 
     boolean isChecked) {
    if(myMenu != null){
     if(buttonView==btn1){
      
      myMenu.findItem(R.id.menuopt1)
       .setVisible(isChecked);
      myMenu.findItem(R.id.menuopt1)
       .setEnabled(isChecked);
     }else if(buttonView==btn2){
      myMenu.findItem(R.id.menuopt2)
       .setVisible(isChecked);
      myMenu.findItem(R.id.menuopt2)
       .setEnabled(isChecked);
     }else if(buttonView==btn3){
      myMenu.findItem(R.id.menuopt3)
       .setVisible(isChecked);
      myMenu.findItem(R.id.menuopt3)
       .setEnabled(isChecked);
     }
    }
    
   }};

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  myMenu = menu;
  return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  switch(item.getItemId()){
  case R.id.menuopt1:
   Toast.makeText(MainActivity.this, 
    "menuopt1", 
    Toast.LENGTH_SHORT).show();
   break;
  case R.id.menuopt2:
   Toast.makeText(MainActivity.this, 
    "menuopt2", 
    Toast.LENGTH_SHORT).show();
   break;
  case R.id.menuopt3:
   Toast.makeText(MainActivity.this, 
    "menuopt3", 
    Toast.LENGTH_SHORT).show();
   break;
  }
  return super.onOptionsItemSelected(item);
 }

}

/res/menu/main.xml and /res/layout/activity_main.xml, refer last exercise "Enable/Disable menu item dynamically".


No comments: