如何从上下文菜单启动 Intent

How do I start an Intent from context Menu

我的片段中有一个包含单个项目的上下文菜单。我想启动另一个 Intent,但似乎该项目无法检测到点击

 override fun onCreateContextMenu(menu: ContextMenu?, v: View?, menuInfo: ContextMenu.ContextMenuInfo?) {
        super.onCreateContextMenu(menu, v, menuInfo)
        menu?.setHeaderTitle("Menu");
        menu?.add(0, 1000, 0, R.string.context_add_content_title)

    }
 override fun onContextItemSelected(item: MenuItem?): Boolean {


            when(item?.itemId){
                1000 ->  startManageContentActivity()
            }

        Log.e("Clicked", "Yes at $item")
        return super.onContextItemSelected(item)
    }

    private fun startManageContentActivity() {
        val intent: Intent = Intent(activity, ManageContentActivity::class.java)
        startActivity(intent)
    }

谁能帮我解决这个问题

我不太了解 kotlin,但我知道 java 它将是:

@Override
public boolean onContextItemSelected(MenuItem item) {

    if (item.getTitle() == getResources().getString(R.string.context_add_content_title)) {
        // do whatever
    }else {
        return  false;
    }
    return true;
}

问题是因为您没有将菜单项添加到上下文菜单。

这个可以工作:

class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    registerForContextMenu(inc_btn)
}

override fun onCreateContextMenu(
    menu: ContextMenu, v: View,
    menuInfo: ContextMenuInfo?) {
    super.onCreateContextMenu(menu, v, menuInfo)
    val inflater = menuInflater
    inflater.inflate(R.menu.sample_menu, menu)
}

override fun onContextItemSelected(item: MenuItem): Boolean {
        Log.d("mlogs", "click")
        if (item.title == "Save") {
            Log.d("mlogs", "SAVE")
        } else {
            return false
        }
        return true
    }
}

别忘了在 menu.xml 中添加菜单项:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/new_game"
        android:title="First"
        app:showAsAction="ifRoom" />
    <item android:id="@+id/help"
        android:title="Second" />
</menu>