Monday, January 23, 2012

Simple Options Menu in Android


  1. Create an Android XML file of Menu type

  2. Add menu options as you preferred. Each menu option should be indicated as <item> XML element.

  3. This is my options.xml file.[sourcecode language="xml"]
    <!--?xml version=<em--><?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:id="@+id/item1" android:title="Edit" android:icon="@android:drawable/ic_menu_edit"></item>
    <item android:id="@+id/item2" android:title="Delete" android:icon="@android:drawable/ic_menu_delete"></item>
    <item android:id="@+id/item3" android:title="Help" android:icon="@android:drawable/ic_menu_help"></item>
    <item android:id="@+id/item4" android:title="More" android:icon="@android:drawable/ic_menu_more"></item>


    </menu>
    [/sourcecode]

  4. My options menu is not just text-based. Each menu item is displayed with a relevant icon. Here I used the icons found in the Android.jar file of my project. You can find such icons using this path
    <app root > --> Android <Your Android platform>  --> android.jar --> res --> drawable-hdpi(icons for menu prefixed with ic_menu)

  5. Override onCreateOptionsMenu and onOptionsItemSelected in your Activity.java file
    [sourcecode language="java"]
    package com.my.option;

    import java.io.Console;
    import java.util.zip.Inflater;

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;

    public class OptionMenuActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflator = getMenuInflater();
    inflator.inflate(R.menu.options, menu);
    return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId() == R.id.item1)
    Log.d("Edit", "Selected : Edit Option");
    if(item.getItemId() == R.id.item2)
    Log.d("Delete", "Selected : Delete Option");
    return super.onOptionsItemSelected(item);
    }
    }
    [/sourcecode]

No comments:

Post a Comment

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...