Android 在 WebView 中启用 longClick

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3449098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:14:40  来源:igfitidea点击:

Enable longClick in WebView

androidbrowserclickwebview

提问by Aymon Fournier

In the browser, you can longClick on URLs. In my WebView, you cannot. How can I make it so you can?

在浏览器中,您可以长按 URL。在我的 WebView 中,您不能。我怎样才能做到你能做到?

回答by Neil Traft

I had this same problem.

我有同样的问题。

Unfortunately, I could not find a way to make the standard browser menu options appear. You have to implement each one yourself. What I did was to register the WebView for context menus with activity.registerForContextMenu(webView). Then I subclassed the WebView and overrode this method:

不幸的是,我找不到让标准浏览器菜单选项出现的方法。你必须自己实现每一个。我所做的是使用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);
    }
}

If you want to do something other than a context menu, then use an OnLongClickListener. However you want to intercept the long click event, the HitTestResultis the key. That's what will allow you to figure out what the user clicked on and do something with it.

如果您想执行上下文菜单以外的其他操作,请使用OnLongClickListener. 然而你想拦截长按事件,HitTestResult是关键。这将使您能够弄清楚用户单击了什么并对其进行操作。

I haven't actually implemented "Save Link" myself, I just included it as an example here. But to do so you would have to do all the processing yourself; you'd have to make an HTTP GET request, receive the response, and then store it somewhere on the user's SD card. There is no way that I know of to directly invoke the Browser app's download activity. Your "Save Link" code will look something like this:

我自己并没有真正实现“保存链接”,我只是将它作为示例包含在这里。但是要这样做,您必须自己进行所有处理;您必须发出 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();
}

回答by kiswa

I would think you could use something like this:

我认为你可以使用这样的东西:

WebView yourWebView;
yourWebView.setLongClickable(true);
yourWebView.setOnLongClickListener(...);

That should let you catch long clicks on the view. What you do after that... that's up to you!

这应该可以让您在视图上长时间点击。之后你要做什么……这取决于你!

回答by LatinSuD

I'd enable Javascript in the webview. Then use onMouseDown() and onMouseUp() to determine the duration of the click.

我会在 webview 中启用 Javascript。然后使用 onMouseDown() 和 onMouseUp() 来确定点击的持续时间。

You can create popup menus in Javascript too (not the standard menus, but your own).

您也可以在 Javascript 中创建弹出菜单(不是标准菜单,而是您自己的菜单)。

Finally you can interact between Javascript and your Android/Java code.

最后,您可以在 Javascript 和您的 Android/Java 代码之间进行交互。

Example of simple interaction between Javascript and an Android app.

Javascript 和 Android 应用程序之间的简单交互示例。

http://code.google.com/p/apps-for-android/source/browse/trunk/Samples/WebViewDemo/assets/demo.html

http://code.google.com/p/apps-for-android/source/browse/trunk/Samples/WebViewDemo/assets/demo.html

http://code.google.com/p/apps-for-android/source/browse/trunk/Samples/WebViewDemo/src/com/google/android/webviewdemo/WebViewDemo.java

http://code.google.com/p/apps-for-android/source/browse/trunk/Samples/WebViewDemo/src/com/google/android/webviewdemo/WebViewDemo.java



Alternatively, you may want to launch real browser instead of using a WebView.

或者,您可能希望启动真正的浏览器而不是使用 WebView。

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://example.com"));
startActivity(intent);

回答by peeyush

I just wanted to copy URL data on long click.
By taking reference from the accepted answer I wrote this.

我只想在长按时复制 URL 数据。
通过参考接受的答案,我写了这个。

    registerForContextMenu(webView);


@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    WebView webView = (WebView) v;
    HitTestResult result = webView.getHitTestResult();

    if (result != null) {
        if (result.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
            String linkToCopy = result.getExtra();
            copyToClipboard(linkToCopy, AppConstants.URL_TO_COPY);
        }
    }
}