开启webview文本选择
时间: 2024-01-29 11:04:00 浏览: 96
您可以使用以下代码在webview中开启文本选择功能:
```java
webView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
final WebView.HitTestResult result = webView.getHitTestResult();
if (result.getType() == WebView.HitTestResult.UNKNOWN_TYPE) {
return false;
}
if (result.getType() == WebView.HitTestResult.EDIT_TEXT_TYPE) {
return true;
}
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setItems(new CharSequence[]{"复制链接地址", "分享链接地址", "复制链接文字"}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
cm.setPrimaryClip(ClipData.newPlainText(null, result.getExtra()));
Toast.makeText(MainActivity.this, "已复制链接地址", Toast.LENGTH_SHORT).show();
break;
case 1:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, result.getExtra());
shareIntent = Intent.createChooser(shareIntent, "分享链接地址");
startActivity(shareIntent);
break;
case 2:
ClipboardManager cm2 = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
cm2.setPrimaryClip(ClipData.newPlainText(null, result.getExtra()));
Toast.makeText(MainActivity.this, "已复制链接文字", Toast.LENGTH_SHORT).show();
break;
}
}
});
builder.show();
return true;
}
});
```
这段代码将在长按webview时弹出一个对话框,其中包含复制链接地址、分享链接地址和复制链接文字等选项。您可以根据需要进行修改和扩展。
阅读全文