近期有项目需要在WebView中选择图像上传,结果发现这里头也算是一个深坑了啊,因为安卓版本碎片化严重,导致选择上传文件的方法因各版本不同有所不同,因此会导致各种点击上传文件而出不来选择框的问题,要解决这个问题,就需要对WebChromeClient的很多方法进行重写来完成了。废话不多说,直接上核心代码吧:
首先对WebChromeClient进行设置,代码如下:
WebSettings settings = webview.getSettings();
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
settings.setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient() {
// Android 3.0 以下
public void openFileChooser(ValueCallback<Uri> valueCallback) {
uploadMessage = valueCallback;
selectImage();
}
// Android 3~4.1
public void openFileChooser(ValueCallback valueCallback, String acceptType) {
uploadMessage = valueCallback;
selectImage();
}
// Android 4.1以上
public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
uploadMessage = valueCallback;
selectImage();
}
// Android 5.0以上
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
uploadMessageAboveL = filePathCallback;
selectImage();
return true;
}
});
selectImage方法代码如下:
private void selectImage() {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "Image Chooser"), 15);
}
Activity返回信息处理如下:
//全局声明,用于记录选择图片返回的地址值
private ValueCallback<Uri> uploadMessage;
private ValueCallback<Uri[]> uploadMessageAboveL;
//......
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 15) {
if (null == uploadMessage && null == uploadMessageAboveL) return;
Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
if (uploadMessageAboveL != null) {
onActivityResultAboveL(requestCode, resultCode, data);
} else if (uploadMessage != null) {
uploadMessage.onReceiveValue(result);
uploadMessage = null;
}
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
if (requestCode != 15 || uploadMessageAboveL == null)
return;
Uri[] results = null;
if (resultCode == Activity.RESULT_OK) {
if (intent != null) {
String dataString = intent.getDataString();
ClipData clipData = intent.getClipData();
if (clipData != null) {
results = new Uri[clipData.getItemCount()];
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item item = clipData.getItemAt(i);
results[i] = item.getUri();
}
}
if (dataString != null)
results = new Uri[]{Uri.parse(dataString)};
}
}
uploadMessageAboveL.onReceiveValue(results);
uploadMessageAboveL = null;
}
以上,WebView选择图像的问题完美解决。
如果这篇文章对你有所帮助,也希望你可以点一下下边的喜欢,如果有什么问题也可以在评论区与我讨论。