Android: Interaction Between WebView and Javascript (mutual parameter calls and value passing), androidwebview
In Android, you can use WebView to load web pages. At the same time, the java code of Android can be called with the javascript code on the web page.
:
(1) Android:
Layout code:
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: focusable = "true" android: focusableInTouchMode = "true" android: orientation = "vertical" android: padding = "8dp" tools: context = ". mainActivity "> <LinearLayout android: layout_width =" match_parent "android: layout_height =" wrap_content "> <EditText android: id =" @ + id/input_et "android: layout_width = "0dp" android: layout_height = "wrap_content" android: singleLine = "true" android: layout_weight = "1" android: hint = "enter the information"/> <Button android: text = "Java call JS" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: onClick = "sendInfoToJs"/> </LinearLayout> <WebView android: id = "@ + id/webView" android: layout_width = "match_parent" android: layout_height = "match_parent"/> </LinearLayout>
Activity Code:
/*** Android WebView interacts with Javascript. */Public class MainActivity extends ActionBarActivity {private WebView webView; @ SuppressLint ({"SetJavaScriptEnabled", "AddJavascriptInterface"}) @ Override protected void onCreate (Bundle savedInstanceState. onCreate (savedInstanceState); setContentView (R. layout. activity_main); webView = (WebView) findViewById (R. id. webView); webView. setVerticalScrollbarOverlay (true); // sets WebView to support JavaScript WebView. getSettings (). setJavaScriptEnabled (true); String url = "http: // 192.168.1.27/js_17_android_webview.html"; webView. loadUrl (url); // call the local java method webView in js. addJavascriptInterface (new JsInterface (this), "AndroidWebView"); // Add a client to support webView. setWebChromeClient (new WebChromeClient ();} private class JsInterface {private Context mContext; public JsInterface (Context context) {this. mContext = con Text;} // call window. AndroidWebView. showInfoFromJs (name) in js to trigger this method. @ JavascriptInterface public void showInfoFromJs (String name) {Toast. makeText (mContext, name, Toast. LENGTH_SHORT ). show () ;}// call the js Code public void sendInfoToJs (View view) {String msg = (EditText) findViewById (R. id. input_et )). getText (). toString (); // call the function showInfoFromJava (msg) webView in js. loadUrl ("javascript: showInfoFromJava ('" + msg + "')");}}
(2) webpage code:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">