在网页视图中,我发现长按时默认选择。但选择后,我们必须点击所选部分才能复制到剪贴板。我想在按下按钮的时候将所选部分复制到剪贴板。我可以让它成为可能请帮助我......
答案 0 :(得分:3)
您可以执行webview的方法javascript:
方法javascript获取元素id,开始位置和结束位置
function(){
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
}
return sel.anchorNode.parentElement.id+':'+sel.anchorOffset+':'+sel.focusOffset;
})();
在webview上执行:
webview.evaluateJavascript(script, new ValueCallback<String>() {
@Override
public void onReceiveValue(String s) {
selectedData = s; //value of javascript return
selectedData = selectedData.replaceAll("\"", "");
String array[] = new String[3];
elementId = array[0];
startPosition=array[1];
endPosition=array[2];
Log.d("WebView runtime", selectedText);
}
});
如果你想获得选择文本,请使用:
function(){
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
}
return sel.text;
})();
要执行此方法的调用,您可以创建自定义回调
private class TesteCallback implements Callback {
private MyWebView mywebview;
private TextMark textmark;
public TesteCallback(MyWebView mywebview) {
this.mywebview = mywebview;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.setTitle("Chose color");
mode.getMenuInflater().inflate(R.menu.pagina2, menu);
return true;
}
/**
* create custom itens, remove useless itens
*/
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
menu.removeItem(android.R.id.selectAll);
// Remove the "cut" option
menu.removeItem(android.R.id.cut);
// Remove the "copy all" option
menu.removeItem(android.R.id.copy);
return true;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
mywebview.pegarSelecao();
textmark = new TextMark();
switch (item.getItemId()) {
case R.id.red:
// do some stuff
break;
case R.id.yellow:
// do some stuff
break;
case R.id.blue:
// do some stuff
break;
default:
break;
}
return false;
}
}//end class
如果您需要使用自定义回调,则需要创建自定义Web视图并调用回调:
public class MyWebView extends WebView {
public MyWebView(Context context) {
super(context);
this.contexto = context;
}
public MyWebView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MyWebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
private ActionMode.Callback mActionModeCallback;
///////////////////////////////////////////
@Override
public ActionMode startActionMode(Callback callback) {
ViewParent parent = getParent();
if (parent == null) {
return null;
}
mActionModeCallback = new TesteCallback(this); //this line call custom callback
return parent.startActionModeForChild(this, mActionModeCallback);
}
}