目标效果:
上下文菜单就多用于列表,长按某一项弹出的菜单框。如图一为ListView,长按会弹出图二所示的菜单,点击菜单某一项会弹出图三所示的吐司。
1.activity_main.xml页面放置ListView控件。
activity_main.xml页面:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <ListView android:id="@+id/lvShow" android:layout_width="fill_parent" android:layout_height="fill_parent"/> </RelativeLayout>
<menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_cut" android:orderInCategory="100" android:showAsAction="never" android:title="剪切"/> <item android:id="@+id/action_rname" android:orderInCategory="100" android:showAsAction="never" android:title="重命名"/> </menu>
package com.example.contextmenu; import java.util.ArrayList; import android.os.Bundle; import android.app.Activity; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /*设置ListVilw显示内容*/ showListView(); } /*设置ListVilw显示内容*/ private void showListView(){ ListView listview=(ListView) findViewById(R.id.lvShow); ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,getData()); listview.setAdapter(adapter); this.registerForContextMenu(listview);//给view注册上下文菜单 } /*构造ListView数据源*/ private ArrayList<String> getData(){ ArrayList<String> list=new ArrayList<String>(); for(int i=0;i<5;i++){ list.add("文件"+(i+1)); } return list; } /*添加上下文菜单内容*/ @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,"粘贴"); MenuInflater inflater=getMenuInflater(); inflater.inflate(R.menu.main, menu);//添加布局 } /*判断当前点击的菜单项*/ @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 R.id.action_cut: Toast.makeText(MainActivity.this,"你选择了剪切",Toast.LENGTH_SHORT).show(); break; case R.id.action_rname: Toast.makeText(MainActivity.this,"你选择了重命名",Toast.LENGTH_SHORT).show(); break; } return super.onContextItemSelected(item); } }