ContextMenu,称为上下文菜单,也就是长按界面不放,弹出的菜单。使用ContextMenu有三个步骤:
(1)调用registerForContextMenu()方法,为视图注册上下文菜单;
(2)重写Activity的onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuInfo)方法,调用Menu的add方法添加菜单项(MenuItem)
(3)重写onContextItemSelected(MenuItem item)方法,响应菜单单击事件;
注:步骤(2)中的方法参数ContextMenuInfo menuInfo有什么作用?
有时候,视图元素需要向上下文菜单传递一些信息,比如该View对应DB记录的ID等,这就要使用ContextMenuInfo。需要传递额外信息的View需要重写getContextMenuInfo()方法,返回一个带有数据的ContextMenuInfo实现类对象。
以下程序参考自《android应用开发详解》
MainActivity.java
import android.os.Bundle; import android.app.Activity; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private TextView contextMenuView; //定义TextView private static final int ITEM1=Menu.FIRST; private static final int ITEM2=Menu.FIRST+1; private static final int ITEM3=Menu.FIRST+2; private static final int ITEM4=Menu.FIRST+3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); contextMenuView=(TextView)findViewById(R.id.contextTest); //注册上下文菜单 registerForContextMenu(contextMenuView); } //重写方法,并添加菜单选项 public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuInfo){ menu.add(0,ITEM1,0,"复制"); menu.add(0,ITEM2,0,"全选"); menu.add(0,ITEM3,0,"分享"); menu.add(0,ITEM4,0,"搜索"); }
//响应菜单事件 public boolean onContextItemSelected(MenuItem item){ switch(item.getItemId()){ case ITEM1: Toast.makeText(this, "You have click 'copy'",Toast.LENGTH_SHORT ).show(); break; case ITEM2: Toast.makeText(this, "You have click 'all copy'",Toast.LENGTH_SHORT ).show(); break; case ITEM3: Toast.makeText(this, "You have click 'share'",Toast.LENGTH_SHORT ).show(); break; case ITEM4: Toast.makeText(this, "You have click 'search'",Toast.LENGTH_SHORT ).show(); break; } return true; } }
activity_main.xml如下 :
<TextView android:id="@+id/contextTest" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="长按屏幕显示ContextMenu" />
代码运行结果如下: