我试图在长按按钮时创建一个浮动上下文菜单。我已经阅读了所有的答案,但我仍然为此让自己发疯。这是我的代码:
R.menu.menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/MnuOpc1" android:title="Opcion1"
android:icon="@drawable/ic_launcher"></item>
<item android:id="@+id/MnuOpc2" android:title="Opcion2"
android:icon="@drawable/ic_launcher"></item>
<item android:id="@+id/MnuOpc3" android:title="Opcion3"
android:icon="@drawable/ic_launcher"></item>
</menu>
OnCreateContextMenu(...)
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
}
onContextItemSelected(...)
@Override
public boolean onContextItemSelected(MenuItem item) {
Log.v("Hello...","I got the switch");
switch (item.getItemId()) {
case R.id.MnuOpc1:
Log.v("Hello...","Option 1");
return true;
case R.id.MnuOpc2:
Log.v("Hello...","Option 2");
return true;
default:
return super.onContextItemSelected(item);
}
我认为上面的所有代码都是正确的,但是在 registerForContextMenu 调用时我遗漏了一些东西:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
linear = (LinearLayout) findViewById(R.layout.main);
registerForContextMenu(linear);
我试过registerForContextMenu(getListView());
但它不起作用,我从 Eclipse 收到一个错误。我究竟做错了什么?