Android上下文菜单ContextMenu
ContextMenu是一种悬浮于主界面上的菜单。当注册到一个View对象上时,默认情况下可以长按View对象约2秒钟呼出上下文菜单。
Context menus do not support item shortcuts and item icons:不支持快捷键和显示图标。
To show a context menu on long click, most clients will want to call registerForContextMenu(View)
and override onCreateContextMenu(ContextMenu, View, ContextMenu.ContextMenuInfo)
.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:id="@+id/myTextView"
android:textSize="20sp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello"
/>
</LinearLayout>
下面是 .java
package com.example.menucontext;
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.TextView;
import android.util.Log;
public class ContextMenuActivity extends Activity {
private static final int C_MENU_NEW = 0;
private static final int C_MENU_OPEN =1;
MenuItem contextmenu_item_new=null;
MenuItem contextmenu_item_open=null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv=new TextView(this);
tv.setText("上下文菜单的载体");
//将上文定义的TextView注册上下文菜单
registerForContextMenu(tv);
setContentView(tv);
}
//上下文菜单,本例会通过长按条目激活上下文菜单
@Override
public void onCreateContextMenu(ContextMenu menu, View view,
ContextMenuInfo menuInfo) {
menu.setHeaderTitle("welsh");
//添加菜单项
contextmenu_item_new=menu.add(0, C_MENU_NEW, 0, "新建");
contextmenu_item_open=menu.add(0,C_MENU_OPEN, 0, "打开");
}
//菜单单击响应
@Override
public boolean onContextItemSelected(MenuItem item){
//获取当前被选择的菜单项的信息
switch(item.getItemId()){
case C_MENU_NEW:
//在这里添加处理代码
break;
case C_MENU_OPEN:
//在这里添加处理代码
break;
}
return true;
}
}
结果图: