Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android webview - change clipboard data when clipboard changed

I am developing web browser using webview. (Android API level 21)

My goal is when user copy certain text in webView, getting that text value and change it.

I used clipboard change event listner, so when event listener capture copy event, getPrimaryClip, change clip data and setPrimaryClip are processing.

But, event listener is still alive so after setPrimaryClip is called, this process is called again and again...

How can I control just one time?

Or Could you suggest other event listener?


Edit I referenced this -> made custom contextual action bar.

And with JavaScript code taught by DevTest(answer for this question), I success to make my goal.

like image 973
Jehyun Shim Avatar asked Oct 24 '25 08:10

Jehyun Shim


1 Answers

The only way to get text selection from a WebView is based on javascript. This is not specific to the action mode, this is how WebView text selection is supposed to be retrieved according to WebView developers' point of view. They deliberately decided to not provide an API to access text selection from Java.

The solution comprise 2 approaches.

With Android API >= 19 you can use evaluateJavascript:

webview.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
    @Override
    public void onReceiveValue(String value)
    {
        Log.v(TAG, "SELECTION:" + value);
    }
});

On older builds your only resort is a custom javascript interface with a single method accepting String, which you should call via webview.loadUrl passing the same thing:

webview.loadUrl("javascript:js.callback(window.getSelection().toString())");

where js is the attached javascript interface:

webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new WebAppInterface(), "js");

and

public class WebAppInterface
{
    @JavascriptInterface
    public void callback(String value)
    {
        Log.v(TAG, "SELECTION:" + value);
    }
}

Answer from Here

UPDATE:

For modifying and copy data (as your comment), Store the selected value in a member variable like "Seleted_Value" and when on clicking copy button (which is handling action mode - search about custom action mode) modify the "Selected_Value" variable and copy to clipboard using :

ClipboardManager clipboard = (ClipboardManager)
        getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("simple text",Selected_Value); 
clipboard.setPrimaryClip(clip);

Details here :

like image 196
Arun Shankar Avatar answered Oct 25 '25 22:10

Arun Shankar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!