Monday, January 23, 2012

How to add a context 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 context_menu.xml file.[sourcecode language="xml"]
    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/item1"   android:title="option1"></item>
    <item android:id="@+id/item2"   android:title="option2"></item>
    </menu>
    [/sourcecode]

  4. Override onCreateContextMenu and onContextItemSelected in your Activity.java file
    Add a button in main.xml to respond our context menu.
    [sourcecode language="java"]
    package com.my.option;

    import java.util.zip.Inflater;
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.ContextMenu;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ContextMenu.ContextMenuInfo;
    import android.widget.Button;

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

    Button b = (Button) findViewById(R.id.button1);
    registerForContextMenu(b);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
    ContextMenuInfo menuInfo) {

    MenuInflater inflator = getMenuInflater();
    inflator.inflate(R.menu.context_menu, menu);

    }

    @Override
    public boolean onContextItemSelected(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.onContextItemSelected(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...