WebView---js调用原生日历控件
2017-02-13 本文已影响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套路非常简单:
- js中通过“jk”来调用native方法,“jk”是在
webView.addJavascriptInterface(this,"jk");
中设置的;
- Java方法用“@JavascriptInterface”注解,标示可以供js调用;
- DatePickerDialog的使用,需要注意的是线程问题。