我的片段中有一个contextMenu,其中只有一个项目。我想启动另一个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)
}
有人可以帮我吗
答案 0 :(得分:0)
我对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;
}
答案 1 :(得分:0)
问题是因为您没有将菜单项添加到上下文菜单中。
这将工作:
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>