Disable, Hide Menu dynamically in android

Frequently used code samples and tutorials
vivekkalady
Site Admin
Posts: 35
Joined: Tue Nov 18, 2014 2:39 pm

Disable, Hide Menu dynamically in android

Postby vivekkalady » Sun Nov 23, 2014 9:27 am

This example shows how to

Also Show/Hide a Menu.
myMenu.findItem(R.id.menuopt1).setVisible(isChecked);

Enable/Disable a Menu item.
myMenu.findItem(R.id.menuopt1).setEnabled(isChecked);


Code: Select all

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,
    "Menu 1 Clicked",
    Toast.LENGTH_SHORT).show();
   break;
  case R.id.menuopt2:
   Toast.makeText(MainActivity.this,
    "Menu 2 Clicked",
    Toast.LENGTH_SHORT).show();
   break;
  case R.id.menuopt3:
   Toast.makeText(MainActivity.this,
    "Menu 3 Clicked",
    Toast.LENGTH_SHORT).show();
   break;
  }
  return super.onOptionsItemSelected(item);
 }

}

Return to “Tutorials & Examples”

Who is online

Users browsing this forum: No registered users and 1 guest

cron