android 上下文菜单详解
时间:2014-05-05 21:41:07
收藏:0
阅读:445
本文使用xml来创建上下文菜单
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/add" android:title="添加" android:orderInCategory="4" /> <item android:id="@+id/delete" android:title="删除" android:orderInCategory="1" /> <item android:id="@+id/query" android:title="查询" android:orderInCategory="2" /> <item android:id="@+id/update" android:title="更新" android:orderInCategory="3" /> </menu>
orderInCategory属性为排列顺序
MyActivity的布局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="弹出上下文菜单" /> </LinearLayout>
MyActivity.java
package com.example.contextMenuTest; import android.app.Activity; import android.os.Bundle; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MyActivity extends Activity { private Button button; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button = (Button) findViewById(R.id.btn); //为按钮注册contextMenu,当你长按按钮的时候就会调用onCreateContextMenu方法 registerForContextMenu(button); } /** * 注意:每次长按注册了contextMenu的控件,都会重新调用该方法 */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { System.out.println("com.example.contextMenuTest.MyActivity.onCreateContextMenu"); getMenuInflater().inflate(R.menu.basic_main, menu); //设置标题栏的图标 menu.setHeaderIcon(R.drawable.ic_launcher); //设置标题栏的文字 menu.setHeaderTitle("请选择操作"); } @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.add: Toast.makeText(this, "你点击了添加!", 1).show(); break; case R.id.delete: Toast.makeText(this, "你点击了删除!", 1).show(); break; case R.id.update: Toast.makeText(this, "你点击了修改!", 1).show(); break; case R.id.query: Toast.makeText(this, "你点击了查询!", 1).show(); break; } return true; } }
评论(0)