Here is source code of the Program to Demonstrate Checkable Menu Items in Android. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.
Main Activity
package com.example.usingcheckablemenuitems; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } /* * When a checkable item is selected, the system calls your respective * item-selected callback method (such as onOptionsItemSelected()). It is * here that you must set the state of the checkbox, because a checkbox or * radio button does not change its state automatically. You can query the * current state of the item (as it was before the user selected it) with * isChecked() and then set the checked state with setChecked() */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.save: case R.id.delete: if (item.isChecked()) item.setChecked(false); else item.setChecked(true); return true; default: return super.onOptionsItemSelected(item); } } }
Menu
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <group android:checkableBehavior="single" > <item android:id="@+id/delete" android:title="Delete"/> <item android:id="@+id/save" android:title="Save"/> </group> </menu>
Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.
advertisement
If you wish to look at all Tutorials, go to Java Android Tutorials.
Related Posts:
- Practice Programming MCQs
- Check Programming Books
- Practice BCA MCQs
- Apply for Computer Science Internship
- Apply for Java Internship