How Do I Hide and Show A Menu Item in The Android ActionBar
How Do I Hide and Show A Menu Item in The Android ActionBar
This example demonstrates how do I hide and show a menu item in the Android ActionBar.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details
to create a new project.
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
ToggleButton button1;
Menu myMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = findViewById(R.id.btnMenuItem);
button1.setOnCheckedChangeListener(onCheckedChangeListener);
}
CompoundButton.OnCheckedChangeListener onCheckedChangeListener = new CompoundButto
CompoundButt
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
https://www.tutorialspoint.com/how-do-i-hide-and-show-a-menu-item-in-the-android-actionbar 1/4
8/8/2020 How do I hide and show a menu item in the Android ActionBar?
if(myMenu != null) {
if (buttonView == button1) {
myMenu.findItem(R.id.menu_action_share).setVisible(isChecked);
myMenu.findItem(R.id.menu_action_share).setEnabled(isChecked);
}
}
}
};
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menuitem, menu);
myMenu = menu;
MenuItem item = menu.findItem(R.id.menu_action_share);
if (item != null) {
item.setVisible(true);
}
return true;
}
}
Step 4 − Right click on res, create menu folder. Right click on the menu folder, create a menu
resource file (menuitem.xml) and add the following code −
Let's try to run your application. I assume you have connected your actual Android Mobile device
with your computer. To run the app from android studio, open one of your project's activity files and
click Run icon from the toolbar. Select your mobile device as an option and then check your
mobile device which will display your default screen −
https://www.tutorialspoint.com/how-do-i-hide-and-show-a-menu-item-in-the-android-actionbar 3/4
8/8/2020 How do I hide and show a menu item in the Android ActionBar?
https://www.tutorialspoint.com/how-do-i-hide-and-show-a-menu-item-in-the-android-actionbar 4/4