01.
package
com.myapp;
02.
03.
import
android.app.Activity;
04.
import
android.content.Context;
05.
import
android.os.Bundle;
06.
import
android.view.Menu;
07.
import
android.webkit.WebView;
08.
import
android.widget.Toast;
09.
10.
11.
public
class
MainActivity
extends
Activity{
12.
13.
@Override
14.
public
void
onCreate(Bundle savedInstanceState) {
15.
super
.onCreate(savedInstanceState);
16.
setContentView(R.layout.activity_main);
17.
18.
19.
WebView WebViw = (WebView) findViewById(R.id.webView1);
20.
WebViw.getSettings().setJavaScriptEnabled(
true
);
21.
WebViw.addJavascriptInterface(
new
JavaScriptInterface(
this
),
"Android"
);
22.
23.
StringBuilder html =
new
StringBuilder();
24.
html.append(
"<html><body><h2>Test WebView</h2>"
);
25.
html.append(
"<input type=\"text\" id=\"txtName\" />"
);
26.
html.append(
"<input type=\"button\" value=\"Say hello\" onClick=\"showAndroidToast(document.getElementById('txtName').value)\" />"
);
27.
28.
html.append(
"<script type=\"text/javascript\">"
);
29.
html.append(
" function showAndroidToast(toast) {"
);
30.
html.append(
" Android.showToast(toast);"
);
31.
html.append(
" }"
);
32.
html.append(
"</script>"
);
33.
34.
WebViw.loadData(html.toString(),
"text/html"
,
"UTF-8"
);
35.
36.
}
37.
38.
public
class
JavaScriptInterface {
39.
Context mContext;
40.
41.
42.
JavaScriptInterface(Context c) {
43.
mContext = c;
44.
}
45.
46.
47.
public
void
showToast(String toast) {
48.
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
49.
}
50.
}
51.
52.
@Override
53.
public
boolean
onCreateOptionsMenu(Menu menu) {
54.
getMenuInflater().inflate(R.menu.activity_main, menu);
55.
return
true
;
56.
}
57.
58.
}