Webview is a button used to interact with the front end. It can load local Html files, and web pages to achieve interactive functions.
WebView can use Android's native JavascriptInterface to communicate between js and java through WebSetting.
Load a local file: webView.loadUrl("file:///android_asset/xxx.html");
Load a webpage: webView.loadUrl("http://baidu.com");
Case: (WebView loads local Html and communicates with JS) Rendering:
Code:
/*** * * WebView loads local files and implements JS click effects * * @author zq * */ public class MainActivity extends Activity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate (savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { // TODO Auto-generated method stub // Get the webview control webView = (WebView) findViewById(R.id.activity_webview); // Get the settings of the WebView WebSettings webSettings = webView.getSettings(); // Set JavaScript to be available, this sentence is required, otherwise everything is in vain webSettings.setJavaScriptEnabled(true); // Add JavaScript interface to webview webView.addJavascriptInterface(new JsInterface(), "control"); // Load html page through webview webView.loadUrl("file:///android_asset/l.html"); } public class JsInterface { @JavascriptInterface public void showToast(String toast) { Toast.makeText(MainActivity.this, toast, Toast.LENGTH_SHORT).show(); } public void log(final String msg) { webView.post(new Runnable() { @Override public void run() { webView.loadUrl("javascript log(" + "'" + msg + "'" + ")"); } }); } } }
js file
function showToast(toast) { javascript:control.showToast(toast); } function log(msg) { consolse.log(msg); }
Add permissions to AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
The code is not fully given, you can download the source code directly