Android interacts with JavaScript

Source: Internet
Author: User

Reprint please explain the source!
KQW Siege Lion
Source: Personal Station | CSDN

This article refers to the introduction of Android and HTML+JS interaction

Load Local HTML
contentWebView = (WebView) findViewById(R.id.webview);// 加载Assets下的HtmlcontentWebView.loadUrl("file:///android_asset/html/test.html");
Enable JavaScript
contentWebView.getSettings().setJavaScriptEnabled(true);contentWebView.addJavascriptInterface(this"android");
How Android calls JavaScript

JavaScript Syntax

< Script  type  = "Text/javascript"  >   function  jsfunction   ()  { document.getElementById ( "content" ). InnerHTML =  "JS method called" ; } function  jsFunctionArg   { document.getElementById (). InnerHTML = " JS Method was called and received parameter:<br/> " + arg; }  </script ;   

Android notation

// 调用JS的jsFunction方法contentWebView.loadUrl("javascript:jsFunction()");// 调用JS的jsFunctionArg方法contentWebView.loadUrl("javascript:jsFunctionArg(‘[Android传递过来的数据]‘)");
JavaScript calls the Android method

Android method

@JavascriptInterfacepublicvoidandroidFunction() {    "Android的方法被调用", Snackbar.LENGTH_SHORT).show();}
@JavascriptInterfacepublicvoidandroidFunction(String text) {    "Android的方法被调用并收到参数 : \n" + text, Snackbar.LENGTH_SHORT).show();}

JavaScript calls

<input type="button" style="width:300px;height:50px;" value="JS调用Android方法" onclick="window.android.androidFunction()" />
<input type="button" style="width:300px;height:50px;" value="JS调用Android带有参数的方法" onclick="window.android.androidFunction(‘[JS传递过来的数据]‘)" />
Codehtml

<html>    <head>        <meta http-equiv="Content-type" Content="text/html;charset=gb2312 ">        <script type="Text/javascript">  function jsfunction(){ document.getElementById ("Content")            . InnerHTML = "JS method is called"; }  function jsfunctionarg(Arg){ document.getElementById (
     
       "Content"). InnerHTML = 
      "JS method is called and receives parameter:<br/>" + arg; }                    
     </script>    </head>    <body>        <H1>HTML page</H1>        <hr/>        <h3><div id="Content">|</div></h3>        <hr/>        <input type="button" style="width:300px;height:50px;" Value="JS calls Android Method" onclick="Window.android.androidFunction ()" />        <br/>        <input type="button" style="width:300px;height:50px;" Value="JS calls Android with parameter method" onclick="Window.android.androidFunction (' [JS passed over data] ' ) " />    </body></html>
Test class
 PackageCom.kongqw.kqwandroidjsdemo;ImportAndroid.annotation.SuppressLint;ImportAndroid.os.Bundle;ImportAndroid.support.design.widget.Snackbar;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.support.v7.widget.Toolbar;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.webkit.JavascriptInterface;ImportAndroid.webkit.WebView; Public  class mainactivity extends appcompatactivity {    PrivateWebView Contentwebview;@SuppressLint({"Javascriptinterface","Setjavascriptenabled","Addjavascriptinterface"})@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        Toolbar Toolbar = (Toolbar) Findviewbyid (R.id.toolbar);        Setsupportactionbar (toolbar); Contentwebview = (WebView) Findviewbyid (R.id.webview);//Load the HTML under assetsContentwebview.loadurl ("File:///android_asset/html/test.html");//Enable JavaScriptContentwebview.getsettings (). setjavascriptenabled (true); Contentwebview.addjavascriptinterface ( This,"Android"); }@JavascriptInterface     Public void androidfunction() {Snackbar.make (Contentwebview,"The Android method is called", Snackbar.length_short). Show (); }@JavascriptInterface     Public void androidfunction(String text) {Snackbar.make (Contentwebview,"The Android method was called and received the parameter: \ n"+ text, Snackbar.length_short). Show (); }@Override     Public Boolean Oncreateoptionsmenu(Menu menu) {Getmenuinflater (). Inflate (R.menu.menu_main, menu);return true; }@Override     Public Boolean onoptionsitemselected(MenuItem Item) {intid = item.getitemid ();if(id = = R.id.action_js_function1) {//Call JS's Jsfunction methodContentwebview.loadurl ("Javascript:jsfunction ()");return true; }Else if(id = = R.id.action_js_function2) {//Call JS's Jsfunctionarg methodContentwebview.loadurl ("Javascript:jsfunctionarg (' [data passed over Android] ')");return true; }return Super. onoptionsitemselected (item); }}

Android interacts with JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.