listview项目删除,但在应用程序重新启动时返回

时间:2018-02-05 16:21:28

标签: android listview android-arrayadapter custom-arrayadapter

我有一个自定义arrayadapter我可以创建我的listview并向其添加项目。我创建一个上下文菜单来删除长按的项目,上下文菜单启动我选择删除项目消失(我庆祝)我重新启动应用程序,项目回来(我尖叫)。这是带有“删除”代码的上下文菜单

@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);
    }
}

在我声明CarAdapter ca;的活动顶部,CarAdapter是我的自定义数组

这里是on create

//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;
  }

1 个答案:

答案 0 :(得分:3)

您的HTMLImageElement列表已加载

cars

但删除时,只能从适配器中删除。

您必须从已创建的汽车ArrayList中删除。

ArrayList<Cars> cars = Utilities.getAllSavedCars(this);