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).

实现步骤:
1、定义一个View对象,并给它注册上下文菜单 :registerForContextMenu(View)
2、重写回调函数: onCreateContextMenu(...)
3、响应点击事件: onContextItemSelected(MenuItem item)
 
main.xml

<?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;
    }
   
}

 

 结果图:

posted @ 2012-08-05 07:37  挡不住会飞的鸡  阅读(486)  评论(0编辑  收藏  举报