ContextMenu对应的是View,每个View都可以设置上下菜单;一般情况下ContextMenu常用于ListView或者Grid
1、首先给View注册上下文菜单registerForContextMenu()
2、添加上下文菜单内容onCreateContextMenu()
-可以通过代码动态添加;
-可以加载xml文件中的菜单项
3、设置菜单点击后响应时间onContextItemSelected()
package com.suo.drawable_conextmenu;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView listview = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showListView();
}
public void showListView() {
listview = (ListView) findViewById(R.id.listview);
ArrayAdapter contextAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,
getdata());
listview.setAdapter(contextAdapter);
// 注册上下文菜单registerForContextMenu()
this.registerForContextMenu(listview);
}
// 添加上下文菜单内容onCreateContextMenu()
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Manage");
menu.setHeaderIcon(R.drawable.ic_launcher);
menu.add(1, 1, 1, "copy");
menu.add(1, 2, 1, "cut");
menu.add(1, 3, 1, "paste");
menu.add(1, 4, 1, "rename");
}
// 设置菜单点击后响应事件onContextItemSelected()
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
Toast.makeText(this, "copy finished", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(this, "cut finished", Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(this, "paste finished", Toast.LENGTH_SHORT).show();
break;
case 4:
Toast.makeText(this, "rename finished", Toast.LENGTH_SHORT).show();
break;
}
return super.onContextItemSelected(item);
}
public ArrayList getdata() {
ArrayList list = new ArrayList();
for (int i = 0; i < 5; i++) {
list.add("文件" + (i + 1));
}
return list;
}
}
- 可以加载xml文件中的菜单项
参考选项菜单引入xml文件
getMenuInflater().inflate(R.menu.main, menu);