android - Android 中的 float 上下文菜单

标签 android android-contextmenu

我试图在长按按钮时创建一个 float 上下文菜单。我已经阅读了所有答案,但我仍然对此感到疯狂。这是我的代码:

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 收到错误。我究竟做错了什么?

最佳答案

您说您正在尝试为按钮创建上下文菜单,但在 onCreate() 中您将上下文菜单注册到 LinearLayout。尽管不知道您实际遇到的错误,但无法判断是否是这样。

关于android - Android 中的 float 上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11109393/

相关文章:

android - 找不到与 Layout_to_left_of 的给定名称匹配的资源

android - 在 Unity3D 中从脚本更改 Android APK 包名称

java - 我的上下文菜单中有一个简单的错误,有人可以解决吗?

android - 如何在 firebaseui 提供的 recyclerview 项目上使用上下文菜单

java - 未知变量或字段 imageURL

java - import com.google.android.gms.location.LocationClient无法解析

Android 手机状态监听器

android - context 和 INSTANCE 静态声明的内存泄漏,我该如何改变它?

android - 带有两个 fragment 的 onContextItemSelected 的问题

android - 上下文菜单上的图标未显示?