在 Webview 4.2.2 (Android Studio) 中选择文件

Chose File In Webview 4.2.2 (Android Studio)

我尝试在 webview 4.2.2 的 html 页面中输入图像文件 但是输入文件不起作用。你有我的问题的解决方案吗? 请帮助我

这是我的代码 (Tambah.java) :

public class Tambah extends Activity {

private TextView text2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tambah);

    final WebView myWebView = (WebView) findViewById(R.id.webPage);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    myWebView.loadUrl("http://192.168.1.104/safa/tambah");
    myWebView.setOnKeyListener(new View.OnKeyListener()
    {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if(event.getAction() == KeyEvent.ACTION_DOWN)
            {
                WebView myWebView = (WebView) v;

                switch(keyCode)
                {
                    case KeyEvent.KEYCODE_BACK:
                        if(myWebView.canGoBack())
                        {
                            myWebView.goBack();
                            return true;
                        }
                        break;
                }
            }

            return false;
        }
    });
}

}

您必须重写 WebChromeClient 中的 onShowFileChooser 方法,如下所示:

mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                mFilePathCallback = filePathCallback;
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                startActivityForResult(intent, PICKFILE_REQUEST_CODE);
                return true;
            }
        });

然后 onActivityResult 执行以下操作:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == PICKFILE_REQUEST_CODE) {
            //Uri result = intent.getData();
            Uri result = intent == null || resultCode != RESULT_OK ? null
                    : intent.getData();
            if(result != null){
                Uri[] resultsArray = new Uri[1];
                resultsArray[0] = result;
                mFilePathCallback.onReceiveValue(resultsArray);
            }
            else
                mFilePathCallback.onReceiveValue(null);

        }
    }

并在 activity 中为您的请求代码定义一个静态整数,例如:

private static final int PICKFILE_REQUEST_CODE = 1;

它应该像魅力一样工作。