Context Menu

A context menu is conceptually similar to the menu displayed when the user performs a "right-click" on a PC. You should use a context menu to provide the user access to actions that pertain to a specific item in the user interface. On Android, a context menu is displayed when the user performs a "long press" (press and hold) on an item.

You can create a context menu for any View, though context menus are most often used for items in a ListView. When the user performs a long-press on an item in a ListView and the list is registered to provide a context menu.

Example:

Context Menu

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/startcontextmenu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Long-Press on me!"
/>
</LinearLayout>


package com.MyContextMenu;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.TextView;
import android.widget.Toast;

public class MyContextMenu extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView textStartContextMenu = (TextView)findViewById(R.id.startcontextmenu);
registerForContextMenu(textStartContextMenu);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub

Toast.makeText(MyContextMenu.this,
String.valueOf(item.getItemId()),
Toast.LENGTH_LONG).show();

return super.onContextItemSelected(item);
}

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, 0, 0, "- A -");
menu.add(0, 1, 0, "- B -");
menu.add(0, 2, 0, "- C -");
menu.add(0, 4, 0, "- D -");
}
}


0 Response to "Context Menu"

Posting Komentar