我正在开发笔记应用。我在每个列表视图项上实现了一个上下文菜单,弹出一个删除选项。选择删除选项后,会弹出一个警告对话框,询问用户是否要删除所选注释。我还有一个控制删除操作的Utilities类。这个问题是我无法为笔记实现正确的逻辑,因为所选的笔记项目不会消失。
Utilities.java
public class Utilities {
/**
* String extra for a note's filename
*/
public static final String EXTRAS_NOTE_FILENAME = "EXTRAS_NOTE_FILENAME";
public static final String FILE_EXTENSION = ".bin";
public static boolean deleteFile(Context context, String fileName) {
File dirFiles = context.getFilesDir();
File file = new File(dirFiles, fileName);
if(file.exists() && !file.isDirectory()) {
return file.delete();
}
return false;
}
}
主要活动
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final Note mLoadedNote = (Note) mListNotes.getAdapter().getItem(info.position);
mLoadedNote.getTitle();
switch (item.getItemId()) {
break;
case R.id.delete:
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this)
.setTitle("Delete " + mLoadedNote.getTitle())
.setMessage("are you sure?")
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mFileName = mListNotes.getAdapter().getItem(info.position) + (Utilities.EXTRAS_NOTE_FILENAME);
if(Utilities.deleteFile(getApplicationContext(), mFileName) ) {
Toast.makeText(MainActivity.this, mLoadedNote.getTitle() + " is deleted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "can not delete the note '" + mLoadedNote.getTitle() + "'", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("NO", null); //do nothing on clicking NO button :P
alertDialog.show();
}
return super.onContextItemSelected(item);
}