我一直在尝试使用以下代码删除 sdcard 上的文件,但它不起作用。这是显示删除选项的上下文菜单,但是当我按下它时没有任何反应,顺便说一句,“pass”是我的应用程序在 sdcard 上创建的目录:
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Context Menu");
menu.add(0, v.getId(), 0, "delete");
menu.add(0, v.getId(), 0, "wtever");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle()=="delete"){function1(item.getItemId());}
else if(item.getTitle()=="wtever"){function2(item.getItemId());}
else {return false;}
return true;
}
public void function1(int id){
Toast.makeText(this, "function 1 called", Toast.LENGTH_SHORT).show();
File folder = Environment.getExternalStorageDirectory();
String fileName = folder.getPath() + "/pass/hello.pdf";
File myFile = new File(fileName);
if(myFile.exists())
myFile.delete();
}
// 列表类
public class PDFListActivity extends ListActivity {
ArrayAdapter<String> adapter;
int clickCounter=0;
ArrayList<String> listItems=new ArrayList<String>();
private File[] imagelist;
String[] pdflist;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlistpdf);
File images=new File(Environment.getExternalStorageDirectory(), "pass");
imagelist = images.listFiles(new FilenameFilter(){
public boolean accept(File dir, String name)
{
return ((name.endsWith(".pdf")));
}
});
pdflist = new String[imagelist.length];
for(int i = 0;i<imagelist.length;i++)
{
pdflist[i] = imagelist[i].getName();
}
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, pdflist));
ListView list=getListView();
registerForContextMenu(list);
}