我有一个自定义数组适配器,我可以创建我的列表视图并向其中添加项目。我创建了一个上下文菜单来删除长按的项目,上下文菜单启动我选择删除项目消失(我庆祝)我重新启动应用程序,项目又回来了(我尖叫)。这是带有我的“删除”代码的上下文菜单
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()){
case R.id.menu_deleteItem:
ca.remove(ca.getItem(info.position));
ca.notifyDataSetChanged();
return true;
default:
return super.onContextItemSelected(item);
}
}
在我声明的 Activity 顶部,CarAdapter ca;
CarAdapter 是我的自定义数组
这是在创建
//this populates the list view
@Override
protected void onResume() {
super.onResume();
main_car_list.setAdapter(null);
ArrayList<Cars> cars = Utilities.getAllSavedCars(this);
//for context menu
registerForContextMenu(main_car_list);
if(cars == null || cars.size() == 0){
Toast.makeText(this,"you have no cars added", Toast.LENGTH_SHORT).show();
return;
}else{
//removed CarAdapter ca and moved CarAdapter up top so could use to delete items
ca = new CarAdapter(this, R.layout.car_list, cars); //from caradapter
main_car_list.setAdapter(ca);
//when click item(car) opens new activity
main_car_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int postion, long l) { //tabbed automatically filled in this
String fileName = ((Cars)main_car_list.getItemAtPosition(postion)).getDateTime() + Utilities.FILE_EXTENSION; //gets filename
Intent viewCar = new Intent(getApplicationContext(),CarDetails.class); //when clicked on item in list opens deails
//this is how pass data between activities
viewCar.putExtra("Car_File", fileName); //Car_File is a key (like naming the file)
startActivity(viewCar);
}
});
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
我从我的实用程序活动中删除汽车的方法
//deletes car
public static boolean deleteCar(Context context, String fileName){
File dir = context.getFilesDir();
File filename = new File(dir,fileName);
if(filename.exists()){
filename.delete();
}
return true;
}