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

效果图


WebView---js调用原生日历控件_第1张图片
效果图.png

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");
    中设置的;
  2. Java方法用“@JavascriptInterface”注解,标示可以供js调用;
  3. DatePickerDialog的使用,需要注意的是线程问题。

你可能感兴趣的:(Android)