Android與JavaScript方法相互調(diào)用
在Android中通過WebView控件,可以實(shí)現(xiàn)要加載的頁面與Android方法相互調(diào)用,我們要實(shí)現(xiàn)WebView中的addJavascriptInterface方法,這樣html才能調(diào)用android方法。
本文引用地址:http://www.butianyuan.cn/article/201609/305031.htm為了讓大家容易理解,寫了一個(gè)簡單的Demo,具體步驟如下:
第一步:新建一個(gè)Android工程,命名為WebViewDemo(這里我在assets里定義了一個(gè)html頁面)。

第二步:修改main.xml布局文件,增加了一個(gè)WebView控件還有Button控件,代碼如下:
view plaincopy to clipboardprint?
android:orientation=vertical
android:layout_width=fill_parent
android:layout_height=fill_parent
>
android:layout_width=fill_parent
android:layout_height=wrap_content
android:text=Welcome to Mr Wei's Blog.
/>
android:id=@+id/webview
android:layout_width=fill_parent
android:layout_height=wrap_content
/>
android:id=@+id/button
android:layout_width=fill_parent
android:layout_height=wrap_content
android:text=Change the webview content
/>
第三步:在assets目錄下新建一個(gè)demo.html文件,代碼如下(這里不知道為何多了mce:這幾個(gè)東東,這樣是對的):
view plaincopy to clipboardprint?
Start GoogleMap
A Demo ----Android and Javascript invoke each other.
Author:Frankiewei
第四步:修改主核心程序WebViewDemo.java,代碼如下:
view plaincopy to clipboardprint?
package com.tutor.webwiewdemo;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
public class WebViewDemo extends Activity {
private WebView mWebView;
private Button mButton;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupViews();
}
//初始化
private void setupViews() {
mWebView = (WebView) findViewById(R.id.webview);
WebSettings mWebSettings = mWebView.getSettings();
//加上這句話才能使用javascript方法
mWebSettings.setJavaScriptEnabled(true);
//增加接口方法,讓html頁面調(diào)用
mWebView.addJavascriptInterface(new Object() {
//這里我定義了一個(gè)打開地圖應(yīng)用的方法
public void startMap() {
Intent mIntent = new Intent();
ComponentName component = new ComponentName(
com.google.android.apps.maps,
com.google.android.maps.MapsActivity);
mIntent.setComponent(component);
startActivity(mIntent);
}
}, demo);
//加載頁面
mWebView.loadUrl(file:///android_asset/demo.html);
mButton = (Button) findViewById(R.id.button);
//給button添加事件響應(yīng),執(zhí)行JavaScript的fillContent()方法
mButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
mWebView.loadUrl(javascript:fillContent());
}
});
}
}
第五步:運(yùn)行上述工程,查看效果。

首界面

點(diǎn)擊按鈕時(shí),html內(nèi)容改變

點(diǎn)擊html的startGoogleMap啟動(dòng)地圖應(yīng)用
評論