Android:如何从webview中选择文本

时间:2011-05-19 12:48:47

标签: android webview copy-paste

我希望允许用户从webview中选择一些文本,并且需要将其作为文本消息发送。请找到选择文本并复制到剪贴板并从剪贴板中提取的方法。我看到很多例子,但没有任何帮助我真的... TIA

编辑
使用 @ orangmoney52 链接中提供的代码。以下更改

getmethod的第二个参数和调用方法第二个参数。如果我给null那就会有警告......哪一个是正确的?

 public void selectAndCopyText() {
     try {
         Method m = WebView.class.getMethod("emulateShiftHeld", Boolean.TYPE); 
            m.invoke(BookView.mWebView, false); 
        } catch (Exception e) {
            e.printStackTrace();
            // fallback
            KeyEvent shiftPressEvent = new KeyEvent(0,0,
                 KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_SHIFT_LEFT,0,0);
            shiftPressEvent.dispatch(this);
        }

}

出现此错误:

 05-26 16:41:01.121: WARN/System.err(1096): java.lang.NoSuchMethodException: emulateShiftHeld  

4 个答案:

答案 0 :(得分:13)

上面的答案看起来很完美,看起来你在选择文字时遗漏了一些东西。因此,您需要仔细检查代码并找到覆盖webview的任何 TouchEvent

我试过下面的代码,它工作得很好......

功能

 private void emulateShiftHeld(WebView view)
    {
        try
        {
            KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
                                                    KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
            shiftPressEvent.dispatch(view);
            Toast.makeText(this, "select_text_now", Toast.LENGTH_SHORT).show();
        }
        catch (Exception e)
        {
            Log.e("dd", "Exception in emulateShiftHeld()", e);
        }
    }

在任何地方调用Above方法(您可以在其click事件中放置一个按钮并调用此方法):emulateShiftHeld(mWebView);

答案 1 :(得分:8)

步骤:1 创建自定义WebView类。 此类将在webview文本上长按时覆盖本机操作栏。 它还处理不同版本的android的选择案例(在4.0以后测试) 此代码使用javascript获取所选文本。

public class CustomWebView extends WebView {
private Context context;
// override all other constructor to avoid crash
public CustomWebView(Context context) {
    super(context);
    this.context = context;
    WebSettings webviewSettings = getSettings();
    webviewSettings.setJavaScriptEnabled(true);
    // add JavaScript interface for copy
    addJavascriptInterface(new WebAppInterface(context), "JSInterface");
}

// setting custom action bar
private ActionMode mActionMode;
private ActionMode.Callback mSelectActionModeCallback;
private GestureDetector mDetector;

// this will over ride the default action bar on long press
@Override
public ActionMode startActionMode(Callback callback) {
    ViewParent parent = getParent();
    if (parent == null) {
        return null;
    }
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        String name = callback.getClass().toString();
        if (name.contains("SelectActionModeCallback")) {
            mSelectActionModeCallback = callback;
            mDetector = new GestureDetector(context,
                    new CustomGestureListener());
        }
    }
    CustomActionModeCallback mActionModeCallback = new CustomActionModeCallback();
    return parent.startActionModeForChild(this, mActionModeCallback);
}

private class CustomActionModeCallback implements ActionMode.Callback {

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        mActionMode = mode;
        MenuInflater inflater = mode.getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false; 
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {

        switch (item.getItemId()) {
        case R.id.copy:
            getSelectedData();
            mode.finish(); 
            return true;
        case R.id.share:
            mode.finish();
            return true;
        default:
            mode.finish();
            return false;
        }
    }
    @Override
    public void onDestroyActionMode(ActionMode mode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            clearFocus();
        }else{
             if (mSelectActionModeCallback != null) {
                 mSelectActionModeCallback.onDestroyActionMode(mode);
             }
             mActionMode = null;
        }
    }
}
private void getSelectedData(){

    String js= "(function getSelectedText() {"+
            "var txt;"+
            "if (window.getSelection) {"+
                "txt = window.getSelection().toString();"+
            "} else if (window.document.getSelection) {"+
                "txt = window.document.getSelection().toString();"+
            "} else if (window.document.selection) {"+
                "txt = window.document.selection.createRange().text;"+
            "}"+
            "JSInterface.getText(txt);"+
          "})()";
    // calling the js function
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        evaluateJavascript("javascript:"+js, null);
    }else{
        loadUrl("javascript:"+js);
    }
}

private class CustomGestureListener extends GestureDetector.SimpleOnGestureListener {
    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        if (mActionMode != null) {
            mActionMode.finish();
            return true;
        }
        return false;
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    // Send the event to our gesture detector
    // If it is implemented, there will be a return value
    if(mDetector !=null)
        mDetector.onTouchEvent(event);
    // If the detected gesture is unimplemented, send it to the superclass
    return super.onTouchEvent(event);
}

}

第2步: 为WebView接口创建单独的类。 这个类列表来自一旦javascript代码被执行的事件

public class WebAppInterface {
Context mContext;

WebAppInterface(Context c) {
    mContext = c;
}

@JavascriptInterface
public void getText(String text) {
    // put selected text into clipdata
    ClipboardManager clipboard = (ClipboardManager)
            mContext.getSystemService(Context.CLIPBOARD_SERVICE);
    ClipData clip = ClipData.newPlainText("simple text",text);
    clipboard.setPrimaryClip(clip);
    // gives the toast for selected text
    Toast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
}
}

第3步: 在res&gt;中为自定义菜单添加menu.xml菜单文件夹

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:id="@+id/copy"
    android:icon="@drawable/ic_action_copy"
    android:showAsAction="always" 
    android:title="copy">
</item>
<item
    android:id="@+id/share"
    android:icon="@drawable/ic_action_share"
    android:showAsAction="always" 
    android:title="share">
</item>

我接受了下面列出的几个链接的帮助来实现这个目标: 谢谢你们。

如何在webview上使用javascript http://developer.android.com/guide/webapps/webview.html#UsingJavaScript

用于注入javascript Why can't I inject this javascript in the webview on android?

用于覆盖默认操作栏 How to override default text selection of android webview os 4.1+?

版本4.0。到4.3文本选择 Webview text selection not clearing

答案 2 :(得分:5)

最简单的方法,虽然不像每个制造商实施的复制/粘贴功能那样漂亮,但如下:

https://bugzilla.wikimedia.org/show_bug.cgi?id=31484

基本上,如果您通过WebChromeClient设置自己的webview.setWebChromeClient(...),则默认情况下会禁用文本选择。要启用它,您的WebChromeClient需要实施以下方法:

//@Override
/**
* Tell the client that the selection has been initiated.
*/
public void onSelectionStart(WebView view) {
    // Parent class aborts the selection, which seems like a terrible default.
    //Log.i("DroidGap", "onSelectionStart called");
}

答案 3 :(得分:0)

@vnshetty,使用@ orangmoney52链接中提供的代码,我几个月前就完成了这个问题。您可以在菜单中创建一个允许您复制文本的按钮。然后,在onOptionsItemSelected中,您可以有这样的子句:

    case R.id.select_and_copy: {
        Toast.makeText(getApplicationContext(), "Select Text", Toast.LENGTH_SHORT).show();
        selectAndCopyText();
        return true;
    }