Wednesday, 1 March 2017

Android Option Menu Example

    activity_main.xml have simple one linear or relative layout by default. For the icons right click on drawable folder and select New->Vector Asset then after added required icons. android:showAsAction=["ifRoom" | "never" | "withText" | "always" | "collapseActionView"] this one is most important for the displaying your menu with icon into menu bar or action bar. For more information refer developer console.
menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_phone"
        android:icon="@drawable/ic_call"
        android:title="Phone"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/action_mail"
        android:icon="@drawable/ic_post"
        android:title="Mail"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_calender"
        android:icon="@drawable/ic_calendar"
        android:title="Calender"
        app:showAsAction="never" />
</menu>
MainActivity.java

package com.androidsimplifycodes.example;

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

public class MainActivity extends AppCompatActivity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_phone:
                Toast.makeText(this, "Phone", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.action_mail:
                Toast.makeText(this, "Mail", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.action_calender:
                Toast.makeText(this, "Calender", Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
Output :