[英]How do I delete an item through the menu?
下面是我的子菜單按鈕的代碼,我正在嘗試使其刪除注釋並返回主列表視圖。 刪除選項現在稱為“紅色”。
我從我的主要活動中復制了刪除代碼,以為它可以工作,但是沒有用。 我對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);
}
在您的切換案例中放置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
它只是很notesList.add()
..您沒有在代碼中的任何地方調用notesList.add()
方法,所以我只是認為它根本是空的..您肯定在那里缺少break語句,但是我想這不是您的原因單擊菜單項后,便箋不會被刪除。 您是將筆記保存在“上一個”(按后退堆棧)活動中嗎? 如果是這樣,您可能會嘗試僅更改setActivityResult()
調用的返回代碼(或在意圖中添加一些其他內容),然后在onActivityResult()
回調中進行檢查。.因為現在您每次通過back關閉活動鍵,便箋被保存( saveAndFinish()
方法); 請更好地描述您實際在哪里保存注釋(到數據庫等)以及要刪除它們的位置..然后我可能會為您提供一些代碼片段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.