The isChecked() method is a part of the MenuItem interface in the Android.view package library. It is used to determine whether the menu item is currently checked or not. The method returns a boolean value indicating the result.
Example 1:
In this example, we have a menu resource file named "menu_main.xml" that defines a menu item with ID "menu_item_id" and the "checkable" attribute is set to "true". Then in the corresponding activity, we reference the menu item and use the isChecked() method to determine if it is checked or not.
menu_main.xml:
Java code:
public class MainActivity extends AppCompatActivity { private MenuItem menuItem;
@Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_item_id) { boolean isChecked = menuItem.isChecked(); // use isChecked() method if (isChecked) { // item is checked } else { // item is not checked } return true; } return super.onOptionsItemSelected(item); } }
Example 2:
In this example, we have a programmatically created menu item that is not initially checked. In a button click listener, we toggle the checked state of the menu item using the setChecked() method and then use the isChecked() method to determine the new state.
Java code:
public class MainActivity extends AppCompatActivity { private Menu menu; private MenuItem menuItem;
@Override public boolean onCreateOptionsMenu(Menu menu) { this.menu = menu; menuItem = menu.add("Programmatically Created Item"); menuItem.setCheckable(true); return true; }
@Override public boolean onOptionsItemSelected(MenuItem item) { if (item == menuItem) { boolean isChecked = menuItem.isChecked(); menuItem.setChecked(!isChecked); // toggle checked state isChecked = menuItem.isChecked(); if (isChecked) { // item is checked } else { // item is not checked } return true; } return super.onOptionsItemSelected(item); } }
Package library: android.view.
Java MenuItem.isChecked - 30 examples found. These are the top rated real world Java examples of android.view.MenuItem.isChecked extracted from open source projects. You can rate examples to help us improve the quality of examples.