Thursday, January 28, 2016

android - How to use Options Menu

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="0dp"
    tools:context=".MainActivity"
    android:background="#fcfdfb"
    >
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        />
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Change This Text Color\nUsing Toolbar Menu"
        android:textSize="50dp"
        android:gravity="center"
        android:textStyle="bold"
        />
</RelativeLayout>
res/menu/toolbar_options_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<!--
    Menu
        A menu resource defines an application menu (Options Menu, Context Menu, or submenu) that
        can be inflated with MenuInflater.
-->
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >
    <!--
        android:showAsAction
            ifRoom
                Only place this item in the app bar if there is room for it. If there is not room
                for all the items marked "ifRoom", the items with the lowest orderInCategory values
                are displayed as actions, and the remaining items are displayed in the overflow menu.
            withText
                Also include the title text (defined by android:title) with the action item. You can
                include this value along with one of the others as a flag set,
                by separating them with a pipe |.
            never
                Never place this item in the app bar. Instead, list the item in the
                app bar's overflow menu.
            always
                Always place this item in the app bar. Avoid using this unless it's critical that
                the item always appear in the action bar. Setting multiple items to always appear
                as action items can result in them overlapping with other UI in the app bar.
            collapseActionView
                The action view associated with this action item (as declared by
                android:actionLayout or android:actionViewClass) is collapsible.
                Introduced in API Level 14.
    -->
    <item
        android:id="@+id/red"
        android:title="Red"
        android:icon="@drawable/ic_palette_red_36dp"
        app:showAsAction="always|withText"
        android:orderInCategory="1"
        />
    <item
        android:id="@+id/green"
        android:title="Green"
        android:icon="@drawable/ic_palette_green_36dp"
        app:showAsAction="ifRoom|withText"
        android:orderInCategory="2"
        />
    <item
        android:id="@+id/blue"
        android:title="Blue"
        android:icon="@drawable/ic_palette_blue_36dp"
        app:showAsAction="ifRoom|withText"
        android:orderInCategory="3"
        />
    <item
        android:id="@+id/maroon"
        android:title="Maroon"
        android:icon="@drawable/ic_palette_maroon_36dp"
        app:showAsAction="ifRoom|withText"
        android:orderInCategory="4"
        />
    <item
        android:id="@+id/orange"
        android:title="Orange"
        android:icon="@drawable/ic_palette_orange_36dp"
        app:showAsAction="never|withText"
        android:orderInCategory="5"
        />
    <item
        android:id="@+id/purple"
        android:title="Purple"
        android:icon="@drawable/ic_palette_purple_36dp"
        app:showAsAction="withText|withText"
        android:orderInCategory="6"
        />
    <item
        android:id="@+id/black"
        android:title="Black"
        android:icon="@drawable/ic_palette_black_36dp"
        app:showAsAction="withText|collapseActionView"
        android:orderInCategory="7"
        />
</menu>
res/values/styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.support.v7.widget.Toolbar;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private RelativeLayout mRelativeLayout;
    private TextView mTextView;
    private Toolbar mToolbar;


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

        // Get the application context
        mContext = getApplicationContext();
        // Get the activity
        mActivity = MainActivity.this;

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mTextView = (TextView) findViewById(R.id.tv);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        // Set a title for toolbar
        mToolbar.setTitle("Android Options Menu Example");
        mToolbar.setTitleTextColor(Color.WHITE);

        /*
            public void setSupportActionBar (Toolbar toolbar)
                Set a Toolbar to act as the ActionBar for this Activity window.

                When set to a non-null value the getActionBar() method will return an ActionBar
                object that can be used to control the given toolbar as if it were a traditional
                window decor action bar. The toolbar's menu will be populated with the Activity's
                options menu and the navigation button will be wired through the standard
                home menu select action.

                In order to use a Toolbar within the Activity's window content the application
                must not request the window feature FEATURE_SUPPORT_ACTION_BAR.

            Parameters
                toolbar : Toolbar to set as the Activity's action bar

        */
        // Set support actionbar with toolbar
        setSupportActionBar(mToolbar);

        // Change the toolbar background color
        mToolbar.setBackgroundColor(Color.parseColor("#FF80D7FF"));
    }


    /*
        public boolean onCreateOptionsMenu (Menu menu)
            Initialize the contents of the Activity's standard options menu. You should place
            your menu items in to menu.

            This is only called once, the first time the options menu is displayed. To update the
            menu every time it is displayed, see onPrepareOptionsMenu(Menu).

            The default implementation populates the menu with standard system menu items. These are
            placed in the CATEGORY_SYSTEM group so that they will be correctly ordered with
            application-defined menu items. Deriving classes should always call through to the
            base implementation.

            You can safely hold on to menu (and any items created from it), making modifications
            to it as desired, until the next time onCreateOptionsMenu() is called.

            When you add items to the menu, you can implement the Activity's
            onOptionsItemSelected(MenuItem) method to handle them there.

        Parameters
            menu : The options menu in which you place your items.
        Returns
            You must return true for the menu to be displayed;
            if you return false it will not be shown.
    */
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        /*
            MenuInflater
                This class is used to instantiate menu XML files into Menu objects.

                For performance reasons, menu inflation relies heavily on pre-processing of XML
                files that is done at build time.
        */
        /*
            public MenuInflater getMenuInflater ()
                Returns a MenuInflater with this context.
        */
        MenuInflater inflater = getMenuInflater();

        /*
            public void inflate (int menuRes, Menu menu)
                Inflate a menu hierarchy from the specified XML resource. Throws InflateException if there is an error.

            Parameters
                menuRes : Resource ID for an XML layout resource to load (e.g., R.menu.main_activity)
                menu : The Menu to inflate into. The items and submenus will be added to this Menu.

        */
        inflater.inflate(R.menu.toolbar_options_menu, menu);
        return true;
    }


    /*
        public boolean onOptionsItemSelected (MenuItem item)
            This hook is called whenever an item in your options menu is selected. The default
            implementation simply returns false to have the normal processing happen (calling the
            item's Runnable or sending a message to its Handler as appropriate). You can use this
            method for any items for which you would like to do processing without
            those other facilities.

            Derived classes should call through to the base class for it to perform
            the default menu handling.

        Parameters
            item : The menu item that was selected.
        Returns
            boolean : Return false to allow normal menu processing to proceed,
                      true to consume it here.
    */
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId()){
            case R.id.red:
                // Set the text color to red
                mTextView.setTextColor(Color.RED);
                return true;
            case R.id.green:
                // Set the text color to green
                mTextView.setTextColor(Color.GREEN);
                return true;
            case R.id.blue:
                // Set the text color to blue
                mTextView.setTextColor(Color.BLUE);
                return true;
            case R.id.maroon:
                // Set the text color to maroon
                mTextView.setTextColor(Color.parseColor("#800000"));
                return true;
            case R.id.orange:
                // Set the text color to orange
                mTextView.setTextColor(Color.parseColor("#FFA500"));
                return true;
            case R.id.purple:
                // Set the text color to purple
                mTextView.setTextColor(Color.parseColor("#800080"));
                return true;
            case R.id.black:
                // Set the text color to black
                mTextView.setTextColor(Color.BLACK);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
build.gradle [dependencies]

compile 'com.android.support:appcompat-v7:23.1.1'