Options Menu Example

Step 1: Project Structure

Step 2. Layout file (activity_main.xml)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <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” tools:context=”.MainActivity” > <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:layout_centerHorizontal=”true” android:layout_centerVertical=”true” android:text=”OptionsMenu Example” tools:context=”.MainActivity” /> </RelativeLayout>

Step 3: Menu file (menu/main.xml)

1 2 3 4 5 6 7 8 9 10 11 <menu xmlns:android=”http://schemas.android.com/apk/res/android” > <item android:id=”@+id/menu_settings” android:orderInCategory=”100″ android:showAsAction=”never” android:title=”@string/action_settings”/> <item android:id=”@+id/item1″ android:title=”Option1″></item> <item android:id=”@+id/item2″ android:title=”Option2″></item> <item android:id=”@+id/item3″ android:title=”Option3″></item> <item android:id=”@+id/item4″ android:title=”Option4″></item> <item android:id=”@+id/item5″ android:title=”Option5″></item> <item android:id=”@+id/item6″ android:title=”Option6″></item> </menu>

Step 4: Source Code (MainActivity.java)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 package com.example.hellomenu1; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.item1: Toast.makeText(this, “Option1”, Toast.LENGTH_SHORT).show(); return true; case R.id.item2: Toast.makeText(this, “Option2”, Toast.LENGTH_SHORT).show(); return true; case R.id.item3: Toast.makeText(this, “Option3”, Toast.LENGTH_SHORT).show(); return true; case R.id.item4: Toast.makeText(this, “Option4”, Toast.LENGTH_SHORT).show(); return true; case R.id.item5: Toast.makeText(this, “Option5”, Toast.LENGTH_SHORT).show(); return true; case R.id.item6: Toast.makeText(this, “Option6”, Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } } }

Step 5: The Output

Leave a Reply

Your e-mail address will not be published. Required fields are marked *