Sunday 14 June 2015

Option menu in android

No comments
Today i explorer a Option menu in android. the Option menu is a one types of menu, they can be used for settings like Delete,Search,Copy,Pest,Rename,Move,More etc.In this example we see how to create simple Option menu in android that contains three menu items.

Let's do fun with code:


CREATE NEW PROJECT
We need:

1) main.xml located here ...res/menu
1) activity_main.xml
2) MainActivity.java

 Step 1: Write code into main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/item1"
        android:title="Item 1"/>
    <item
        android:id="@+id/item2"
        android:title="Item 2"/>
    <item
        android:id="@+id/item3"
        android:title="Item 3"/>

</menu>

Step 2: Write code into activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Click option menu to View simple menu" />

</LinearLayout>

Step 3: Write code into MainActivity.java

package dev.androidapplink.optionmenuapp;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

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 Or in Hardware
// control
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

// code here as u wish to do operation. i put simple toast
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(getApplicationContext(), "Item 1 Selected",
Toast.LENGTH_LONG).show();
return true;

case R.id.item2:
Toast.makeText(getApplicationContext(), "Item 2 Selected",
Toast.LENGTH_LONG).show();
return true;

case R.id.item3:
Toast.makeText(getApplicationContext(), "Item 3 Selected",
Toast.LENGTH_LONG).show();
return true;

default:
return super.onOptionsItemSelected(item);
}
}

}
Step 4: Now Run Your Project:



No comments :

Post a Comment

Follow me Share