How to Create Option Menu in Android

In this tutorial how to create Option Menu in Android in shown.

Code:

activity_main.xml

<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:paddingBottom=”@dimen/activity_vertical_margin”
android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
tools:context=”.MainActivity” >

<TextView
android:id=”@+id/tv1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentLeft=”true”
android:layout_alignParentTop=”true”
android:layout_marginLeft=”61dp”
android:layout_marginTop=”60dp”
android:text=”” />

<ImageView
android:id=”@+id/img1″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_alignParentBottom=”true”
android:layout_centerHorizontal=”true”
android:src=”@drawable/desert” />

</RelativeLayout>

res/menu/main.xml

<menu xmlns:android=”http://schemas.android.com/apk/res/android” >
<item android:id=”@+id/item1″ android:title=”Desert”></item>
<item android:id=”@+id/item2″ android:title=”JellyFish”></item>
<item android:id=”@+id/item3″ android:title=”Koala”></item>
<item android:id=”@+id/item4″ android:title=”LightHouse”></item>
<item android:id=”@+id/item5″ android:title=”Penguins”></item>

</menu>

MainActivity.java

package com.example.demo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity{

ImageView iv;
TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv=(ImageView)findViewById(R.id.img1);
tv=(TextView)findViewById(R.id.tv1);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.item1:
tv.setText(“Desert Selected”);
iv.setImageResource(R.drawable.desert);
return true;
case R.id.item2:
tv.setText(“JellyFish Selected”);
iv.setImageResource(R.drawable.jellyfish);
return true;
case R.id.item3:
tv.setText(“Koala Selected”);
iv.setImageResource(R.drawable.koala);
return true;
case R.id.item4:
tv.setText(“LightHouse Selected”);
iv.setImageResource(R.drawable.lighthouse);
return true;
case R.id.item5:
tv.setText(“Penguin Selected”);
iv.setImageResource(R.drawable.penguins);
return true;
default:
return super.onOptionsItemSelected(item);
}
}

}

Add a Comment

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