正文
Android 菜单 之 上下文菜单ContextMenu
小程序:扫一扫查出行
【扫一扫了解最新限行尾号】
复制小程序
【扫一扫了解最新限行尾号】
复制小程序
所谓上下文菜单就是当我们长按某一个文件时弹出的菜单
操作这个菜单我们要重写onCreateContextMenu()方法
如上一篇文章一样,对于这个菜单中选型的操作也有动态添加和xml文件添加两种方法
首先是动态添加
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("文件操作"); //上下文菜单的标题
menu.setHeaderIcon(R.mipmap.ic_launcher);//图标
menu.add(1,1,1,"复制");
menu.add(1,2,1,"粘贴");
menu.add(1,3,1,"剪切");
menu.add(1,4,1,"重命名"); }
然后是xml文件添加
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("文件操作"); //上下文菜单的标题
menu.setHeaderIcon(R.mipmap.ic_launcher);//图标
MenuInflater infalter = getMenuInflater(); //
infalter.inflate(R.menu.main,menu);//实例化main布局 }
xml文件的布局
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu_item1"
android:orderInCategory="100" <!-- 决定菜单中选项的排列顺序 数字越大优先级越低,排位越靠后-->
android:showAsAction="never" <!-- 表示是否默认显示出来-->
android:title="复制"></item>
<item
android:id="@+id/menu_item2"
android:orderInCategory="100"
android:showAsAction="never"
android:title="粘贴"></item>
<item
android:id="@+id/menu_item3"
android:orderInCategory="100"
android:showAsAction="never"
android:title="剪切"></item>
<item
android:id="@+id/menu_item4"
android:orderInCategory="100"
android:showAsAction="never"
android:title="重命名"></item>
</menu>
对ContextMenu的监听
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_item1:
Toast.makeText(MainActivity.this, "你选择了复制", Toast.LENGTH_SHORT).show();
break;
case R.id.menu_item2:
Toast.makeText(MainActivity.this, "你选择了粘贴", Toast.LENGTH_SHORT).show();
break;
case R.id.menu_item3:
Toast.makeText(MainActivity.this, "你选择了剪切", Toast.LENGTH_SHORT).show();
break;
case R.id.menu_item4:
Toast.makeText(MainActivity.this, "你选择了重命名", Toast.LENGTH_SHORT).show();
break;
}
return super.onContextItemSelected(item);
}