Android之Context Memu

Menu 之 Context Menu
类似于PC机上的“右键”选项菜单,而在Android 中则在用户”长按“时显示,它可以在所有示图里出现,只是比较常见于“ListView"。
与options menu 类似,应用它也是三步走:
一、将Activity 改成 ListActivity,这里采用对列表示图进行学习,创建 Context Menu
 重写方法:onCreateContextMenu
例:
        @Override 

public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuInfo)
        {
        //这里可以采用扩展Layout文件来添加菜单项
        menu.add("First");
        menu.add("Second");
        super.onCreateContextMenu(menu, v, menuInfo);
        }

 
二、与用户的交互,重写方法:onContextItemSelected
  @Override

        publicboolean  onContextItemSelected(MenuItem item)
        {
        String itemTitle="Your select context menu item is: "+(String)item.getTitle();
        Toast.makeText(getApplicationContext(), itemTitle,Toast.LENGTH_LONG)
            .show();
        
        return super.onContextItemSelected(item);
        }

三、将context menu 注册到View:
在onCreate方法里:registerForContextMenu(getListView());
我这里是给ListView添加的context menu;
当然还有给列表示图提供内容的方法:
       private void ShowListView()

 {

        
        String [] citys=new String[]{
                "BeiJing","ShangHai","GuangZhou","ShengZhen"
        };
        
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.menu_items,citys);
        
        setListAdapter(adapter);
        
        }

这样,我们的onCreate方法变成了:
   
@Override 

        publicvoid onCreate(Bundle savedInstanceState) 
        {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ShowListView();
        
           registerForContextMenu(getListView());
          }

四、资源布局文件夹:
main.xml:
   <?xml version="1.0" encoding="utf-8"?>

   <ListView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/list" 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        
>    
    </ListView>

menu_items.xml
    <?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width
="match_parent"
        android:layout_height
="match_parent"
        android:id
="@+id/tv">
    </TextView>
posted @ 2011-12-04 01:12  Bluer  阅读(692)  评论(4编辑  收藏  举报