WebView---js调用原生日历控件

作者: 姜康 | 来源:发表于2017-02-13 22:51 被阅读836次

效果图


效果图.png

html文件


<!doctype html>
<html>
<head>
    <script>
        function showDatePickerDialog(){
            jk.showDatePickerDialog();
        }
    </script>
</head>
<body>
    <div class = "test">
        <button onclick="showDatePickerDialog()">打开日历选择器</button>
    </div>
</body>
</html>

Android


    public class WebActivity extends AppCompatActivity {

    @BindView(R.id.tv_web_title)
    TextView tvWebTitle;
    @BindView(R.id.web_progress_bar)
    ProgressBar webProgressBar;
    @BindView(R.id.web_view)
    WebView webView;


    private WebSettings settings;

    private Calendar calendar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        ButterKnife.bind(this);

        calendar = Calendar.getInstance();

        initWebView();

        webView.loadUrl("file:///android_asset/test.html");


    }

    @SuppressLint("JavascriptInterface")
    private void initWebView() {
        settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);

        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new WebViewClient());
        webView.addJavascriptInterface(this,"jk");
    }

    @JavascriptInterface
    public void showDatePickerDialog(){
        final DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        webView.loadUrl("javascript:alert('success!')");
                    }
                });
            }
        },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

说明


这个demo套路非常简单:

  1. js中通过“jk”来调用native方法,“jk”是在
webView.addJavascriptInterface(this,"jk");

中设置的;

  1. Java方法用“@JavascriptInterface”注解,标示可以供js调用;
  2. DatePickerDialog的使用,需要注意的是线程问题。

相关文章

网友评论

    本文标题:WebView---js调用原生日历控件

    本文链接:https://www.haomeiwen.com/subject/cfgtwttx.html