Challange 3 - Delete Photos by Context Menu


#1

Following is my solution to this last challenge question in Chapter 20.

  1. Create menu resource file in res/menu, name it crime_photo_delete.xml

[code]<?xml version="1.0" encoding="utf-8"?>

[/code]
  1. In CrimeFragment.java, implement:

[code] @Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
getActivity().getMenuInflater().inflate(R.menu.crime_photo_delete, menu);
}

@Override
public boolean onContextItemSelected(MenuItem item){
    switch(item.getItemId()){
        case R.id.menu_delete_photo:
            if (mCrime.getPhoto() != null){
                String path = getActivity().getFileStreamPath(mCrime.getPhoto().getFilename()).getAbsolutePath();
                File f = new File(path);
                f.delete();
                mCrime.setPhoto(null);
                mPhotoView.setImageDrawable(null);
            }
            return true;
    }
    return super.onContextItemSelected(item);
}[/code]
  1. In CrimeFragment.java, register your context menu:

mPhotoView = (ImageView)v.findViewById(R.id.crime_imageView); registerForContextMenu(mPhotoView);

this is basically same logic as per chapter 18, pp.284-285