Enable longClick in WebView

Viewed 23457

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

6 Answers

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

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

Based on @peeyush answer with shorter code:

webView.setOnLongClickListener { view ->
    val result = (view as WebView).hitTestResult
    extra?.let { link ->
        // do sth with link
    }
    true
}

I'm using the following code to detect longclicks on links:

webView.setLongClickable(true);
webView.setOnLongClickListener(view -> {
    WebView.HitTestResult hitTestResult = ((WebView) view).getHitTestResult();
    if (hitTestResult.getExtra() == null || !Patterns.WEB_URL.matcher(hitTestResult.getExtra()).matches()) {
        return false;
    }
    String link = hitTestResult.getExtra();
    // do whatever you want with the link
});
Related