我有一个上下文对我的片段中有一个项目。我想启动另一个意图,但似乎该项目无法检测到点击
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
}
}
不要忘记在菜单中添加菜单项:
<?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>