解决webview嵌套网页,上传图片和文件点击无反应问题

package com.jsxf.jscqmlbmb.View;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.jsxf.jscqmlbmb.Controller.view.BaseFragment;
import com.jsxf.jscqmlbmb.Model.Final.OnlyID;
import com.jsxf.jscqmlbmb.R;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

/**
 * Created by Administrator on 2016/11/30 0030.
 * Web页面
 */
public class WebFragment extends BaseFragment {

    private WebView webView;
    private View view;
    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;
    @Nullable
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (null != view) {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (null != parent) {
                parent.removeView(view);
            }
        }
        else {
            view = inflater.inflate(R.layout.fragment_web, container, false);
            if(getResources().getString(R.string.test_url) != null)
            {
                if(!getResources().getString(R.string.test_url).isEmpty())
                {
                    ViewIni(view,getResources().getString(R.string.test_url));// 控件初始化
                }
                else
                {
                    ViewIni(view, "http://OnlyID.NTEPARAMETER(getActivity()));
                }
            }

        }
        webView.setWebChromeClient(new WebChromeClient() {
            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                Log.i("test", "openFileChooser 1");
                uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
                Log.i("test", "openFileChooser 2");
                uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  > 4.1.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Log.i("test", "openFileChooser 3");
                uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  >= 5.0
            public boolean onShowFileChooser(WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                Log.i("test", "openFileChooser 4:" + filePathCallback.toString());
                uploadFiles = filePathCallback;
                openFileChooseProcess();
                return true;
            }
        });
    return view;
}

    private void ViewIni(View view,String url)
    {
        //实例化WebView对象
        webView = (WebView) view.findViewById(R.id.webview);
        //设置WebView属性,能够执行Javascript脚本
        webView.getSettings().setJavaScriptEnabled(true);
        //加载需要显示的网页
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if( url.startsWith("http:") || url.startsWith("https:") ) {
                    return false;
                }

                // Otherwise allow the OS to handle things like tel, mailto, etc.
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity( intent );
                return true;
            }
        });
        webView.loadUrl(url);
        //设置Web视图
        //setContentView(webView);
    }
    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i, "选择文件"), 0);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (uploadFile != null) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFile.onReceiveValue(result);
                        uploadFile = null;
                    }
                    if (uploadFiles != null) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFiles.onReceiveValue(new Uri[]{result});
                        uploadFiles = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (uploadFile != null) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }
            if (uploadFiles != null) {
                uploadFiles.onReceiveValue(null);
                uploadFiles = null;
            }
        }
    }

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在 Android WebView 中实现点击上传图片的功能,需要做以下几个步骤: 1. 在 WebView 中启用 JavaScript: ```java webView.getSettings().setJavaScriptEnabled(true); ``` 2. 为 WebView 设置 WebChromeClient: ```java webView.setWebChromeClient(new WebChromeClient() { // For Android 5.0+ @Override public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) { if (mFilePathCallback != null) { mFilePathCallback.onReceiveValue(null); } mFilePathCallback = filePathCallback; Intent intent = fileChooserParams.createIntent(); try { startActivityForResult(intent, REQUEST_SELECT_FILE); } catch (ActivityNotFoundException e) { mFilePathCallback = null; Toast.makeText(MainActivity.this, "Cannot open file chooser", Toast.LENGTH_SHORT).show(); return false; } return true; } // For Android < 5.0 public void openFileChooser(ValueCallback<Uri> uploadMsg) { openFileChooser(uploadMsg, null); } // For Android 3.0+ public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { mUploadMessage = uploadMsg; Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("*/*"); startActivityForResult(Intent.createChooser(intent, "File Chooser"), FILECHOOSER_RESULTCODE); } }); ``` 这里的 `onShowFileChooser()` 方法是为了支持 Android 5.0 及以上版本的文件上传, `openFileChooser()` 方法是为了支持 Android 3.0 至 Android 4.4 版本的文件上传。在 `onActivityResult()` 方法中处理选择的文件并返回给 WebView: ```java @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == FILECHOOSER_RESULTCODE) { if (null == mUploadMessage) return; Uri result = data == null || resultCode != RESULT_OK ? null : data.getData(); mUploadMessage.onReceiveValue(result); mUploadMessage = null; } else if (requestCode == REQUEST_SELECT_FILE) { if (mFilePathCallback == null) return; Uri[] results = null; // Check that the response is a good one if (resultCode == Activity.RESULT_OK) { if (data == null) { // If there is not data, then we may have taken a photo if (mCameraPhotoPath != null) { results = new Uri[]{Uri.parse(mCameraPhotoPath)}; } } else { String dataString = data.getDataString(); ClipData clipData = data.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)}; } } } mFilePathCallback.onReceiveValue(results); mFilePathCallback = null; } } ``` 3. 在 HTML 中添加上传文件的代码: ```html <input type="file" id="fileInput" name="fileInput" multiple> ``` 这里的 `id` 和 `name` 两个属性都必须为 `fileInput`,否则在 WebView 中无法触发文件上传事件。同时,为了支持多选文件,可以将 `multiple` 属性设置为 `true`。 4. 在 JavaScript 中触发文件上传事件: ```javascript document.getElementById("fileInput").click(); ``` 这里的 `click()` 方法是为了模拟用户点击上传文件按钮。当用户点击上传文件按钮时,WebView 就会弹出文件选择框。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值