首页 > 代码库 > Android ContextMenu的使用
Android ContextMenu的使用
ContextMenu介绍:
如果一个View注册了上下文菜单,那么当长按该View时便会弹出一个浮动菜单,来供选择下一步操作。
实现这个功能需要调用setOnCreateContextMenuListener来注册一个监听器,那么它和注册长按监听器setOnLongClickListener有什么区别呢?下面会在代码中加以测试,通过添加打印发现,用户对某个View长按之后,首先触发的是onLongClick函数,执行onLongClick操作,然后根据onLongClick的返回值判断是不是执行OnCreateContextMenuListener函数;如果onLongClick返回false,则会继续执行OnCreateContextMenuListener函数,如果返回true,忽略OnCreateContextMenuListener函数。
代码如下:
public class MainActivity extends ActionBarActivity { ImageView mImageView ; MyContextMenuClickListener mContextListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_main); mImageView = (ImageView) findViewById(R.id.image); mContextListener = new MyContextMenuClickListener(); mImageView.setOnCreateContextMenuListener(mContextListener); //test mImageView.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View arg0) { // TODO Auto-generated method stub Log.d("Test", "onLongClick"); return false; } }); } private class MyContextMenuClickListener implements OnCreateContextMenuListener , OnMenuItemClickListener{ @Override public boolean onMenuItemClick(MenuItem item) { // TODO Auto-generated method stub switch(item.getItemId()){ case R.id.open: Log.d("Test", "click open"); break; case R.id.delete: Log.d("Test", "click delete"); break; case R.id.remove: Log.d("Test", "click remove"); break; default: break; } return true; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { // TODO Auto-generated method stub Log.d("Test", "onCreateContextMenu"); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); LayoutInflater layoutInflater = getLayoutInflater(); View view = (View) layoutInflater.inflate( R.layout.menu_header, null); menu.setHeaderView(view); MenuItem open = menu.findItem(R.id.open); open.setOnMenuItemClickListener(mContextListener); MenuItem delete = menu.findItem(R.id.delete); delete.setOnMenuItemClickListener(mContextListener); MenuItem remove = menu.findItem(R.id.remove); remove.setOnMenuItemClickListener(mContextListener); } } }
context_menu.xml
<?xml version="1.0" encoding="UTF-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <group android:id="@+id/CONTEXT_MENU"> <item android:id="@+id/delete" android:title="delete"/> <item android:id="@+id/open" android:title="open"/> <item android:id="@+id/remove" android:title="remove"/> </group> </menu>
menu_header.xml
<?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="wrap_content" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is a Test" /> </LinearLayout>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。