DEV Community

Cover image for How to create an option menu with checkbox in Android, Java
dev-aspires
dev-aspires

Posted on

How to create an option menu with checkbox in Android, Java

Picture tutorial

Android menus, are one of the most important components of every modern android application, it provides a means of allowing developers display certain functionalities such as Settings, Search, About app, etc.
The Option menu, is one of the types of menu available in android. It is positioned at the toolbar of some android application. Option menu can be more complex and may require additional components to perform certain functions. Components such as Radion Buttons, Checkboxes, etc, can be used with a menu layout. However, in the cause of this tutorial, we will be buiding a Dark Option menu with several checkboxes.
This tutorial will be divided into five(5) steps for easy understanding and guide.

Step 1: Create a new project, File/New project/input the name of the app as MenuCheckBoxTutorial.

Step 2: Navigate to the res/layout/activity_main.xml, add the following code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#FF000000">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:padding="5dp"
        android:background="#FF000000">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/PopUpDarkMenu"/>

    </android.support.design.widget.AppBarLayout>
</LinearLayout>
Enter fullscreen mode Exit fullscreen mode

In Step 2, we are creating a simple Dark layout for the Linear layout and Tool bar, take note of the attribute app:popupTheme="@style/PopUpDarkMenu" it will be used to add styles to our menu.

Step 3: Create a menu file res/menu/menu_item.xml.

In the menu_item.xml file, we are going to define the content of our menu layout. If you look closely at the tutorial result, the first menu item has a sub-menu, to create a sub-menu under an item, we will create a new menu under the first menu item. For the check box, we will used the android: clickable= "true"; which will be used to display the checkbox icon on our menu item.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/click_action"
        android:title="Click Action">
        <menu>
            <item
                android:id="@+id/item"
                android:title="Item"/>
        </menu>
    </item>
    <item
        android:id="@+id/hide_tracks"
        android:title="Hide Short Tracks"
        android:checkable="true"/>

    <item
        android:id="@+id/show_tracks"
        android:title="Show Track Duration"
        android:checkable="true"/>

    <item
        android:id="@+id/show_overflow"
        android:title="Show Overflow"
        android:checkable="true"/>

    <item
        android:id="@+id/round_corners"
        android:title="Round Corners"
        android:checkable="true"/>

    <item
        android:id="@+id/fast_scrollers"
        android:title="Fast Scroller"
        android:checkable="true"/>

    <item
        android:id="@+id/multi_select"
        android:title="Multi select"
        />

</menu>
Enter fullscreen mode Exit fullscreen mode

Step 4: Navigate to the res/values/style.xml file.

In the style.xml file, we will defined the look of our menu. Create a new style with name "PopUpDarkMenu" and the add the below code:

<resources>
   <style name="PopUpDarkMenu" parent="Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
        <item name="android:textColor">#ffffff</item>
        <item name="android:colorBackground">#444444</item>

        <item name="colorControlNormal">#ffffff</item>   <!-- normal border color change as you wish -->
        <item name="colorControlActivated">#ffffff</item> <!-- activated color change as you wish -->       
    </style>

</resources>
Enter fullscreen mode Exit fullscreen mode

android:textColor is used to set the color of our menu layout text.
colorControlNormal is used to set the border color of the check box.
colorControlActivated is used to set the color of a checked checkbox.

Step 5 : Navigate to the MainActivity.class. Add the following codes.

package com.mycompany.checkbox;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity
{

    @Override
    protected void onCreate (Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu)

    {
        getMenuInflater().inflate(R.menu.list_item, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected (MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.hide_tracks:

                if (item.isChecked())
                {

                    item.setChecked(false);
                }
                else
                {
                    item.setChecked(true);
                    Toast.makeText(getApplication(), "Track Hidden", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.show_tracks:
                if (!item.isChecked())
                {
                    item.setChecked(true);

                    Toast.makeText(getApplication(), "Track Shown", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    item.setChecked(false);
                }
                break;
            case R.id.show_overflow:
                if (!item.isChecked())
                {
                    item.setChecked(true);

                    Toast.makeText(getApplication(), "Overflown", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    item.setChecked(false);
                }
                break;
            case R.id.round_corners:
                if (!item.isChecked())
                {
                    item.setChecked(true);

                    Toast.makeText(getApplication(), "Round Corners", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    item.setChecked(false);
                }
                break;
            case R.id.fast_scrollers:
                if (!item.isChecked())
                {
                    item.setChecked(true);

                    Toast.makeText(getApplication(), "Fast Scrollers enabled", Toast.LENGTH_SHORT).show();
                }
                else
                {

            item.setChecked(false);
                }
                break;
        }
        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

In the Above code snippet, aside the oncreate method, we also have two other methods, the onCreateOptionMenu(Menu menu) and onOptionItemSelected(Menu item).

The onCreateOnptionMenu (Menu menu) This function accept one argument, which is our menu. However, inorder to create out menu, we need to inflate it to the activity_main.xml, this can be done using the getMenuInflater().inflate()
The inflate method is used to pass our menu_item.xml layout to the menu object.
The onCreateOptionMenu (Menu item) will return a boolean value, however for the cause of this tutorial the return value is true.
The second method is the onOptionItemSelected (Menu item)
While the onCreateOnptionMenu (Menu menu) is used to create our menu, the onOptionItemSelected (Menu item) is used to handle onclick event for each menu item in our menu. It accept one argument, which represents a particular item in our menu list.
The item.getItemById() is used to find any item id that matches the id passed, we will be using the switch statement to handle multiple id.
The item.setChecked(boolean b) is used to check if the item check box is checked or not.

Conclusion
Understanding how menus works will be helpful to you as a developer, in this tutorial I have explained in details with code snippet, on how to implement checkboxes on menu in your android applications.

Discussion (0)