Android Example to make menu option in Action bar

      No Comments on Android Example to make menu option in Action bar

You might have noticed that when you create a new Android project.In the source for MainActivity.java,the following code is generated:-

@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;
	}

This code is responsible for creating menu.

You can specify how menu items are displayed in an action bar.If a menu item is displayed in a action bar, it is called an action item and can be clicked directly in the action bar. Let us see example:-

MainActivity.java

package com.example.scan;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

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;
	}

}

res>menu>main.xml

main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_settings"/>

    <item
        android:id="@+id/menu_test"
        android:orderInCategory="10"
        android:showAsAction="ifRoom"
        android:title="Scan 1"/>
    
    <item
        android:id="@id/menu_test"
        android:orderInCategory="10"
        android:showAsAction="ifRoom"
        android:title="Scan 2"/>
</menu>

OUTPUT:-

Leave a Reply

Your email address will not be published. Required fields are marked *