Webview识别当前选中的类型 HitTestResult
在Webview中通过HitTestResult可以识别当前触碰到网页上的元素类型,通过这个方法可以实现:长按文本选中,长按图片保存等功能。
首先通过getHitTestResult()方法获取Webview中的HitTestResult对象:
WebView.HitTestResult result = webView.getHitTestResult();
HitTestResult对象中有两个变量,分别保存点击类型mType和点击的数据mExtra:
private int mType;
private String mExtra;
通过方法getType()获取打开type的类型:
/**
* Gets the type of the hit test result. See the XXX_TYPE constants
* defined in this class.
*
* @return the type of the hit test result
*/
public int getType() {
return mType;
}
其中点击类型mType有如下几种定义:
public static class HitTestResult {
/**
* Default HitTestResult, where the target is unknown.
*/
public static final int UNKNOWN_TYPE = 0;
/**
* @deprecated This type is no longer used.
*/
@Deprecated
public static final int ANCHOR_TYPE = 1;
/**
* HitTestResult for hitting a phone number.
*/
public static final int PHONE_TYPE = 2;
/**
* HitTestResult for hitting a map address.
*/
public static final int GEO_TYPE = 3;
/**
* HitTestResult for hitting an email address.
*/
public static final int EMAIL_TYPE = 4;
/**
* HitTestResult for hitting an HTML::img tag.
*/
public static final int IMAGE_TYPE = 5;
/**
* @deprecated This type is no longer used.
*/
@Deprecated
public static final int IMAGE_ANCHOR_TYPE = 6;
/**
* HitTestResult for hitting a HTML::a tag with src=http.
*/
public static final int SRC_ANCHOR_TYPE = 7;
/**
* HitTestResult for hitting a HTML::a tag with src=http + HTML::img.
*/
public static final int SRC_IMAGE_ANCHOR_TYPE = 8;
/**
* HitTestResult for hitting an edit text area.
*/
public static final int EDIT_TEXT_TYPE = 9;
...
}
通过方法getExtra()获取对应type的附加信息,可以为null:
/**
* Gets additional type-dependant information about the result. See
* {@link WebView#getHitTestResult()} for details. May either be {@code null}
* or contain extra information about this result.
*
* @return additional type-dependant information about the result
*/
@Nullable
public String getExtra() {
return mExtra;
}
依据以上这些方法,即可在网页长按的时候获取网页中点击到的元素,进而实现长按文本选中,长按图片保存等功能。
webView.setOnLongClickListener {
val result = webView.hitTestResult
val type = result.type
when (type) {
WebView.HitTestResult.EDIT_TEXT_TYPE -> {//选中的文字类型}
WebView.HitTestResult.PHONE_TYPE -> {//处理拨号}
WebView.HitTestResult.EMAIL_TYPE -> {//处理Email}
WebView.HitTestResult.GEO_TYPE -> {//地图类型}
WebView.HitTestResult.SRC_ANCHOR_TYPE -> {//超链接}
WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE -> {//带有链接的图片类型}
WebView.HitTestResult.IMAGE_TYPE -> {//处理长按图片的菜单项
var data: String? = result.extra //获取图片
}
WebView.HitTestResult.UNKNOWN_TYPE -> {//未知}
}
false
}
精彩的人生需要浪漫、无畏和勇气。