6

I've poured over similar questions but can't find the answer. I want to be able to long press the user-uploaded images in my webview to save them (like you can in a browser). Any help?

Update:

The context menu is popping up now with my own custom item "Save Image". I can even successfully toast msgs. How do I go about saving the image though? Is the image that's being long clicked being passed to my menu item?

        public boolean onLongClick(View v) {
            openContextMenu(v);
            return true;
        }
        @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);
        }
        @Override
        public boolean onContextItemSelected(MenuItem item) {
          AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
          switch (item.getItemId()) {
          case R.id.save_image:
              Toast.makeText(this, "save failed",
                    Toast.LENGTH_LONG).show();
              return true;
          default:
            return super.onContextItemSelected(item);
          }
        }
Reno
  • 33,594
  • 11
  • 89
  • 102
Andy
  • 75
  • 1
  • 8
  • Did you ever manage this? Is there more to the code? I have a WebView where I could like to implement this and I don't think there's enough code here. – RED_ Apr 20 '13 at 18:48

1 Answers1

9

First register the WebView for context menus like so: activity.registerForContextMenu(webView)

@Override
protected void onCreateContextMenu(ContextMenu menu) {
    super.onCreateContextMenu(menu);

    HitTestResult result = getHitTestResult();

    MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {
                // do the menu action
                return true;
        }
    };

    if (result.getType() == HitTestResult.IMAGE_TYPE ||
            result.getType() == HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {

        menu.setHeaderTitle(result.getExtra());
        menu.add(0, ID_SAVEIMAGE, 0, "Save Image").setOnMenuItemClickListener(handler);
    }

To save you images simply use this

Community
  • 1
  • 1
Reno
  • 33,594
  • 11
  • 89
  • 102
  • Where do I invoke registerForContextMenu()? – Andy Nov 02 '11 at 03:50
  • I've had some success setting up the context menu using xml. The menu pops up on long presses now with the only item being "Copy URL". I'm not sure which protocal to use to make the item actually copy the URL. – Andy Nov 03 '11 at 19:20
  • Thanks for your help Reno. How do I mark my question as answered? – Andy Feb 21 '12 at 08:23