Android WebView JavaScript交互
今天介绍一下,Android中Webview与JavaScript的交互,首先是在布局文件里添加webview控件:
- <WebView
- android:id="@+id/webview"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" />
然后是在manifest里添加权限:
- <uses-permission android:name="and
要是webview能够与JavaScript交互,首先需要webview要启用JavaScript:
- WebSettings webSettings = myWebView.getSettings();
- webSettings.setJavaScriptEnabled(true);
然后创建JavaScript的接口:
- 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();
- }
- }
给webview添加JavaScript接口:
- myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
本地JavaScript文件:
- <input type="button" value="Say hello" onClick="showAndroidToast(‘Hello Android!‘)" />
- <script type="text/javascript">
- function showAndroidToast(toast) {
- Android.showToast(toast);
- }
- </script>
整个代码如下:
- 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() {
- // 加载 asset 文件
- String tpl = getFromAssets("web_tpl.html");
- myWebView.loadDataWithBaseURL(null, tpl, "text/html", "utf-8", null);
- }
- /*
- * 获取html文件
- */
- 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 "";
- }
- }
运行效果:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。