首页 > 代码库 > Android 上下文菜单实现
Android 上下文菜单实现
1.覆盖Activity的onCreateContenxtMenu()方法,调用Menu的add方法添加菜单项(MenuItem)。
2.覆盖Activity的onContextItemSelected()方法,响应上下文菜单菜单项的单击事件。
3.调用registerForContextMenu()方法,为视图注册上下文菜单。
JAVA代码:
packageEOE.local.contextMenu;
importandroid.app.ListActivity;
importandroid.os.Bundle;
importandroid.view.ContextMenu;
importandroid.view.Menu;
importandroid.view.MenuItem;
importandroid.view.ContextMenu.ContextMenuInfo;
importandroid.view.View;
importandroid.widget.AdapterView.AdapterContextMenuInfo;
importandroid.widget.ArrayAdapter;
importandroid.util.Log;
publicclassMainActivityextendsListActivity{
privatestaticfinalintITEM1=Menu.FIRST;
privatestaticfinalintITEM2=Menu.FIRST+1;
privatestaticfinalintITEM3=Menu.FIRST+2;
/**Calledwhentheactivityisfirstcreated.*/
@Override
public void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
showListView();
//为ListView的所有item注册ContextMenu
registerForContextMenu(getListView());
//这里的registerForContextMenu()也可以用下面的语句替代
//getListView().setOnCreateContextMenuListener(this);
}
privatevoidshowListView(){
String[]mString=newString[]{
"路飞-MonkeyDLuffy",
"奈美-Nami",
"卓洛-Zoro",
"山治-Sanji",
"尼可·罗宾-Ms.AllSunday",
"乌索普-usoppu",
"托尼托尼·乔巴-TonyTonyChopper",
};
ArrayAdapter<String>mla=newArrayAdapter<String>(MainActivity.this,
R.layout.main,mString);
MainActivity.this.setListAdapter(mla);
}
//上下文菜单,本例会通过长按条目激活上下文菜单
@Override
publicvoidonCreateContextMenu(ContextMenumenu,Viewview,
ContextMenuInfomenuInfo){
menu.setHeaderTitle("人物简介");
//添加菜单项
menu.add(0,ITEM1,0,"特长");
menu.add(0,ITEM2,0,"战斗力");
menu.add(0,ITEM3,0,"经典语录");
}
//菜单单击响应
@Override
publicbooleanonContextItemSelected(MenuItem item){
//获取当前被选择的菜单项的信息
//AdapterContextMenuInfo info=(AdapterContextMenuInfo)item.getMenuInfo();
//Log.i("braincol",String.valueOf(info.id));
switch(item.getItemId()){
caseITEM1:
//在这里添加处理代码
break;
caseITEM2:
//在这里添加处理代码
break;
caseITEM3:
//在这里添加处理代码
break;
}
returntrue;
}
}
main.xml布局文件:
<?xmlversion="1.0"encoding="utf-8"?>
<TextViewxmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myTextView"
android:textSize="20sp"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/hello"
/>
Android 上下文菜单实现