2

I am building an android application where a webpage( like "https://www.youtube.com/" ) is loaded on a webView. Now in that WebPage, there are some Hyperlink's.

Once an user long press on any of Hyperlink a list open and there are many feature's like copy link, open link in next tap and copy text. Now the issue that I am facing. I am not able to copy the text on that anchor tag where user long press.

I need when any user long press on any hyperlink and select copy text that hyperlink text should be copied. Is there any I can achieve this?

My long press return title and url.

I had refer a lot of link like see

Hitesh Matnani
  • 309
  • 1
  • 5
  • 20

2 Answers2

1

First, you need to listen for View.OnLongClickListener. You can do that very easily by setting a listener on the WebView. Listener has to return a Boolean, return false if you want the copy, cut and paste on text selection or return true

webView.setOnLongClickListener { view ->
    // run things on long click on any element in the webview
    return@setOnLongClickListener false
}

Then create a Handler

val handler = Handler { message ->
    val bundle = message.data

    for (key in bundle.keySet()) {
        Log.d(TAG, "KEY: $key, VALUE: ${bundle.get(key)}")
    }
    val linkText = bundle.get("title") // here is your link text   

    return@Handler true
}

Now you need to obtain the message (this code has to go inside the OnLongClickListener)

val message = handler.obtainMessage()
webView.requestFocusNodeHref(message)

Copying text to the ClipBoard got a little bit complicated.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as android.content.ClipboardManager
    val clipData = android.content.ClipData.newPlainText("text label", "text to clip")
    clipboardManager.primaryClip = clipData
} else {
    val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as android.text.ClipboardManager
    clipboardManager.text = "text to clip"
}
Jeeva
  • 3,975
  • 3
  • 23
  • 47
0

Well, I'm doing the same thing today.

finally I use bellow method:

1.Saving whole html content in onPageFinished().

  1. Use WebView.HitTestResult.getExtra() to get url.

  2. then substring the text among href link tag.

A clunky way, hope it can help you.

FL.S
  • 23
  • 3