我已经阅读过WebView中选择文本的所有内容:
android 4.x:Text Selection in webview
Android: how to select texts from webview
等等。
我写了一个简单的测试程序,这里是源代码:
package com.example.webviewbug;
import android.os.Bundle;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.ClipboardManager.OnPrimaryClipChangedListener;
import android.content.Context;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
public WebView webView1;
public Button button1;
private ClipboardManager mClipboard;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.webView1 = (WebView) findViewById(R.id.webView1);
this.webView1.loadUrl("http://moscow2013.hol.es/reest.html");
this.button1 = (Button) findViewById(R.id.button1);
this.button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
emulateShiftHeld(webView1);
}
});
this.mClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
mClipboard
.addPrimaryClipChangedListener(new OnPrimaryClipChangedListener() {
@Override
public void onPrimaryClipChanged() {
System.out.println("SOME CLIPBOAR HAPPENED");
}
});
}
private void emulateShiftHeld(WebView view) {
try {
KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
shiftPressEvent.dispatch(view);
registerForContextMenu(webView1);
webView1.emulateShiftHeld();
if (mClipboard != null) {
String text = mClipboard.getText().toString();
Toast.makeText(this, "select_text_now " + text,
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("dd", "Exception in emulateShiftHeld()", e);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
我永远无法在webView上获取所选文本,只有当我使用默认的WebView ActionBar并在其中单击Copy。
我需要做些什么才能复制所选文字?