如何通过菜单删除项目?

时间:2014-02-06 18:27:29

标签: java android

下面是我的子菜单按钮的代码,我试图删除该注释并返回主列表视图。删除选项现在称为“红色”。

我从我的主要活动中复制了我的删除代码,认为它可行,但事实并非如此。我对android编码很新,所以请帮助。

这是我在Main Activity.java中删除的方式

    @Override
public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {

    AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
    currentNoteId = (int)info.id;
    menu.add(0, MENU_DELETE_ID, 0, "Delete");
}

@Override
public boolean onContextItemSelected(MenuItem item) {

    if (item.getItemId() == MENU_DELETE_ID) {
        Noteitem note = notesList.get(currentNoteId);
        datasource.remove(note);
        refreshDisplay();

    }

    return super.onContextItemSelected(item);
}

这是我的NoteEditorActivity.java的代码 我再次尝试删除,但我似乎无法弄清楚如何从子菜单中删除注释。

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_exit:
        EditText et = (EditText)findViewById(R.id.noteText);
        if (et.length() > 0) {
            saveAndFinish();
        } 
            else 
        {
        finish();
            }

    case R.id.menu_red:
        currentNoteId = (int) MENU_DELETE_ID;  
        datasource.remove(note);
        return true;  


        default:
            return super.onOptionsItemSelected(item);
    }

2 个答案:

答案 0 :(得分:0)

在您的开关案例中添加break语句

switch (item.getItemId()) 
    {
        case R.id.action_exit:
            EditText et = (EditText)findViewById(R.id.noteText);
            if (et.length() > 0){
                saveAndFinish();
            }else{
                finish();
            }
        //you are missing this!!!
        break;

        case R.id.menu_red:
            datasource.remove(note);
            finish();   
        break;

        default:
            return super.onOptionsItemSelected(item);
        break;
    }

请尝试阅读此处:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

答案 1 :(得分:0)

它只是很奇怪..你没有在你的代码中的任何地方调用notesList.add()方法,所以我认为它根本就是空的.. 你肯定错过了那里的break语句,但我想这并不是你在单击菜单项后没有删除你的注释的问题。您是否在“之前”(就后台堆叠)活动中保存了您的注释?如果是这样,您可能会尝试仅更改setActivityResult()调用的返回代码(或向intent添加一些额外内容),然后在onActivityResult()回调中检查它。 因为现在每次通过后退键关闭活动时,都会保存注释(调用saveAndFinish()方法); 请更好地描述你实际保存笔记的地方(到数据库左右)以及你想要删除它们的地方......我可能会为你提供一些代码片段。

相关问题