在浏览器中,您可以长按URL.在我的WebView中,你不能.我怎么能这样做呢?
我有同样的问题.
不幸的是,我找不到一种方法来显示标准的浏览器菜单选项.你必须自己实现每一个.我所做的是为上下文菜单注册WebView activity.registerForContextMenu(webView)
.然后我将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 options for an image. //set the header title to the image url menu.setHeaderTitle(result.getExtra()); menu.add(0, ID_SAVEIMAGE, 0, "Save Image").setOnMenuItemClickListener(handler); menu.add(0, ID_VIEWIMAGE, 0, "View Image").setOnMenuItemClickListener(handler); } else if (result.getType() == HitTestResult.ANCHOR_TYPE || result.getType() == HitTestResult.SRC_ANCHOR_TYPE) { // Menu options for a hyperlink. //set the header title to the link url menu.setHeaderTitle(result.getExtra()); menu.add(0, ID_SAVELINK, 0, "Save Link").setOnMenuItemClickListener(handler); menu.add(0, ID_SHARELINK, 0, "Share Link").setOnMenuItemClickListener(handler); } }
如果您想要执行上下文菜单以外的操作,请使用OnLongClickListener
.但是你要拦截长按事件,这HitTestResult
是关键.这将使您能够弄清楚用户点击了什么并使用它做了些什么.
我自己实际上没有实现"保存链接",我只是将它作为示例包含在这里.但要做到这一点,你必须自己做所有的处理; 您必须发出HTTP GET请求,接收响应,然后将其存储在用户SD卡的某个位置.我不知道直接调用浏览器应用程序的下载活动.您的"保存链接"代码将如下所示:
HitTestResult result = getHitTestResult(); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(result.getExtra()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { URL url = new URL(result.getExtra()); //Grabs the file part of the URL string String fileName = url.getFile(); //Make sure we are grabbing just the filename int index = fileName.lastIndexOf("/"); if(index >= 0) fileName = fileName.substring(index); //Create a temporary file File tempFile = new File(Environment.getExternalStorageDirectory(), fileName); if(!tempFile.exists()) tempFile.createNewFile(); InputStream instream = entity.getContent(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); //Read bytes into the buffer ByteArrayBuffer buffer = new ByteArrayBuffer(50); int current = 0; while ((current = bufferedInputStream.read()) != -1) { buffer.append((byte) current); } //Write the buffer to the file FileOutputStream stream = new FileOutputStream(tempFile); stream.write(buffer.toByteArray()); stream.close(); }
我认为你可以使用这样的东西:
WebView yourWebView; yourWebView.setLongClickable(true); yourWebView.setOnLongClickListener(...);
这应该可以让您在视图中获得长时间的点击.你之后做了什么......这取决于你!