安卓开发中长按弹出菜单的创建方法:
1.首先给View注册上下文菜单registerForContextMenu();
2.添加上下文菜单内容onCreateContextMenu():
---可以通过代码动态添加;
---可以加载xml文件中的菜单项;
3.设置菜单点击后响应事件onContextItemSelected();
运行效果图如下:
activity_main.xml代码如下:
<RelativeLayout
android:layout_width="match_parent"
......此处省略
>
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/listview"
/>
</RelativeLayout>
MainActivity.java代码如下:
......此处省略
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showListView();
}
/**
*设置listview的显示内容
*/
private void showListView(){
ListView listview = findViewById(R.id.listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,getData());
listview.setAdapter(adapter);
this.registerForContextMenu(listview);
}
@Override
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu,v,menuInfo);
//设置Menu显示内容
menu.setHeaderTitle("文件操作");
menu.setHeaderIcon(R.drawable.ic_launcher);
menu.add(1,1,1,"复制");
menu.add(1,2,1,"粘贴");
menu.add(1,3,1,"剪切");
menu.add(1,4,1,"重命名");
}
@Override
public boolean onContextItemSelected(MenuItem item){
switch(item.getItemId()){
case 1:
Toast.makeText(MainActivity.this,"点击复制",Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(MainActivity.this,"点击粘贴",Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(MainActivity.this,"点击剪切",Toast.LENGTH_SHORT).show();
break;
case 4:
Toast.makeText(MainActivity.this,"点击重命名",Toast.LENGTH_SHORT).show();
break;
}
return super.onContextItemSelected(item);
}
/**
*构造listview显示的数据
*/
private ArrayList<String> getData(){
ArrayList<String> list = new ArrayList<String>();
for(int i=0;i<5;i++){
list.add("文件"+(i+1));
}
return list;
}