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

时间:2017-07-24 11:47:26

标签: android android-webview android-4.2-jelly-bean

我尝试在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;
        }
    });
}

}

1 个答案:

答案 0 :(得分:2)

您必须覆盖onShowFileChooser中的WebChromeClient方法,如下所示:

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);

        }
    }

并为您的活动中的请求代码定义静态int,如:

private static final int PICKFILE_REQUEST_CODE = 1;

它应该像魅力一样工作。