Today, WebView with JavaScript in Android, the first is to add WebView controls to the layout file:
[HTML]View Plaincopy
- <WebView
- android:id="@+id/webview"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" />
Then add the permissions in the manifest:
[HTML]View Plaincopy
- <uses-permission android:name= " and
If WebView can interact with JavaScript, you first need to WebView to enable javascript:
[HTML]View Plaincopy
- WebSettings websettings = mywebview.getsettings ();
- Websettings.setjavascriptenabled (TRUE);
Then create the JavaScript interface:
[Java]View Plaincopy
- Public class Webappinterface {
- Context Mcontext;
- /** instantiate the interface and set the context * /
- Webappinterface (Context c) {
- Mcontext = C;
- }
- /** Show A toast from the Web page * /
- @JavascriptInterface
- public void Showtoast (String toast) {
- Toast.maketext (Mcontext, Toast, Toast.length_short). Show ();
- }
- }
To add a JavaScript interface to WebView:
[HTML]View Plaincopy
- Mywebview.addjavascriptinterface (New Webappinterface (This), "Android");
Local JavaScript files:
[JavaScript]View Plaincopy
- <input type="button" value="Say Hello" onclick="showandroidtoast (' Hello android! ')"/>
- <script type="Text/javascript" >
- function Showandroidtoast (toast) {
- Android.showtoast (toast);
- }
- </script>
The entire code is as follows:
[Java]View Plaincopy
- Public class Mainactivity extends Activity {
- private WebView Mywebview;
- @Override
- protected void OnCreate (Bundle savedinstancestate) {
- super.oncreate (savedinstancestate);
- Setcontentview (R.layout.activity_main);
- Mywebview = (WebView) Findviewbyid (R.id.webview);
- WebSettings websettings = Mywebview.getsettings ();
- Websettings.setjavascriptenabled (true);
- Mywebview.addjavascriptinterface (new Webappinterface (this), "Android");
- Processwebstring ();
- }
- public class Webappinterface {
- Context Mcontext;
- /** instantiate the interface and set the context * /
- Webappinterface (Context c) {
- Mcontext = C;
- }
- /** Show A toast from the Web page * /
- @JavascriptInterface
- public void Showtoast (String toast) {
- Toast.maketext (Mcontext, Toast, Toast.length_short). Show ();
- }
- }
- private void processwebstring () {
- //Load Asset file
- String TPL = getfromassets ("web_tpl.html");
- Mywebview.loaddatawithbaseurl (null, TPL, "text/html", "Utf-8", null);
- }
- /*
- * Get HTML files
- */
- Public string Getfromassets (String fileName) {
- try {
- InputStreamReader Inputreader = new InputStreamReader (
- Getresources (). Getassets (). open (FileName);
- BufferedReader Bufreader = new BufferedReader (Inputreader);
- String line = "";
- String Result = "";
- While (line = Bufreader.readline ()) = null)
- Result + = line;
- return Result;
- } catch (Exception e) {
- E.printstacktrace ();
- }
- return "";
- }
- }
Operating effect:
Android WebView JavaScript interaction