android的context menu上下文菜单,长按某一选项,就会显示出来。
SDK上的描述:Context Menu A floating list of menu items that appears when the user performs a long-press on a View.
(一)Standup Timer中的例子
< menu xmlns:android ="http://schemas.android.com/apk/res/android" >
< item android:id ="@+id/deleteTeam" android:title ="@string/delete"
android:icon ="@android:drawable/ic_menu_delete" />
</ menu >
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super .onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.meetings_context_menu, menu);
}
接下来是处理菜单的点击事件
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (item.getItemId()) {
case R.id.delete_meeting:
postionOfMeetingToDelete = info.position;
showDialog(CONFIRM_DELETE_MEETING_DIALOG);
return true ;
default :
return super .onContextItemSelected(item);
}
}
这里我们使用 AdapterContextMenuInfo 来获取上下文菜单 获取对应VIEW 的信息。.position 在这里返回了ListActivity中的位置,
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout.teams);
// 将右键菜单注册给List 控件
registerForContextMenu(getListView());
}
(二)我的项目 :移动图书馆 中的例子
通过学习上面的开源项目之后,自由也完善了正在做的项目:
输入关键字进行搜索之后,进去结果显示界面,然后通过对每一个ListView绑定单击监听器和长按截听器(集Context Menu)。
首先第一步,绑定单击监听器:
list = (ListView)findViewById(R.id.mylist); list.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { //通过getItemAtPosition()判断点击的是哪个item,然后强制转化为所某一类型, //总的来说,如若需要重写ListView中的onListItemClick(即响应该项被单击),获取该具体项时,
//其类型由构造ListView的适配器决定。 HashMap<String,String> t = (HashMap<String,String>) arg0.getItemAtPosition(arg2); Toast.makeText(getApplicationContext(), t.get("bookName"),Toast.LENGTH_SHORT).show(); } });总的来说,如若需要重写ListView中的onListItemClick(即响应该项被单击),获取该具体项时,其类型由构造ListView的适配器决定。我的使用的是SimpleAdapter。
//创建适配器 SimpleAdapter sa = new SimpleAdapter( this, booklist, R.layout.main, new String [] {"bookName","bookAuthor","press","date","preserveNum","lendableNum","manageNum"} , new int [] {R.id.bookmane,R.id.author,R.id.press,R.id.date,R.id.preserve,R.id.lendable,R.id.manage} );
HashMap<String,String> t = (HashMap<String,String>) arg0.getItemAtPosition(arg2);
单击某项时,效果如下:
覆盖以下两个方法:
@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.booklist_context, menu); } @Override public boolean onContextItemSelected(MenuItem item) { switch(item.getItemId()){ case R.id.buy_book: Toast.makeText(this, "点击了购书推荐",3000).show(); return true; case R.id.detail: Toast.makeText(this, "点击了书籍详细信息",3000).show(); return true; default: return super.onContextItemSelected(item); } }
registerForContextMenu(list);