让菜单出现: 实现Activity或Fragment中的onCreateContextMenu()方法。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main,menu);
return true;
// return false;
}
自定义menu的样式
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/i_add_item"
android:title="add"/>
<item android:id="@+id/i_rem_item"
android:title="rem"/>
<item android:id="@+id/i_http_item"
android:title="http"/>
<item android:id="@+id/i_tel_item"
android:title="tel"/>
</menu>
设置菜单的点击事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = null;
switch (item.getItemId()){
case R.id.i_add_item:
Toast.makeText(this,item.getTitle(),Toast.LENGTH_SHORT).show();
case R.id.i_http_item:
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.baidu.com"));
break;
case R.id.i_tel_item:
intent = new Intent("com.example.jing.ACTION_START");
break;
default:
;
Toast.makeText(this,item.getTitle(),Toast.LENGTH_SHORT).show();
}
if (intent != null){
startActivity(intent);
}
return true;
}
创建上下文菜单
- 通过调用registerForContextMenu()方法把View对象注册给被关联的内容菜单
- 实现Activity或Fragment中的onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) 方法。(当被注册的View对象接受到一个长按(long-click)事件时,系统会调用你的onCreateContextMenu()方法)
- 实现onContextItemSelected()回调方法(处理点击事件)
//onContextItemSelected()方法中获取
AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();