我在Android应用程序中实现上下文菜单时遇到了一些困难。我的第一个问题是我试图在OnCreate中实现OnCreateContextMenu,但我一直收到错误说:
void是变量onCreateContextMenu
的无效类型
我通过将onCreateContextMenu
放在OnCreate之外来修复此问题。现在我的问题在于OnContextItemSelected
。我的错误发生在该行:public boolean onContextItemSelected(MenuItem menu)
。错误是:
- 实现android.view.View.OnLongClickListener.onLongClick
- 语法错误,插入“}”以完成MethodBody
以下是代码:
BaconStripsButton.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
boolean onContextItemSelected(MenuItem item)
{
if (item.itemId() = 0)
{
Toast ringtone = Toast.makeText(startingPoint.this, "Ringtone added Successfully!", Toast.LENGTH_SHORT);
return true;
}
return false;
}
}
});
任何帮助将不胜感激。谢谢,贾斯汀
答案 0 :(得分:1)
您可以使用ListView并在活动的OnCreate中实现onCreateContextMenu。
像这样:myList.setOnCreateContextMenuListener(new OnCreateContextMenuListener(){
@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
// add some sublist
menu.setHeaderTitle(R.string.collect_title);
menu.add(0, 1, 0, R.string.delete_string);
menu.add(0, 2, 0, R.string.move_to_project_string);
menu.add(0, 3, 0, R.string.move_to_action_string);
}
});
答案 1 :(得分:1)
无需使用onContextItemSelected Inside onlongClick of button.Just Override OnContextItemSelected();并将ContextMenu注册到btn.No需要setOnlongClickListener。
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
然后覆盖
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.edit:
editNote(info.id);
return true;
case R.id.delete:
deleteNote(info.id);
return true;
default:
return super.onContextItemSelected(item);
}
} 然后最后registerContextMenu(按钮);