標籤:
今天介紹一下,Android中Webview與JavaScript的互動,首先是在布局檔案裡添加webview控制項:
[html] view plaincopy
- <WebView
- android:id="@+id/webview"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" />
然後是在manifest裡添加許可權:
[html] view plaincopy
- <uses-permission android:name="and
要是webview能夠與JavaScript互動,首先需要webview要啟用JavaScript:
[html] view plaincopy
- WebSettings webSettings = myWebView.getSettings();
- webSettings.setJavaScriptEnabled(true);
然後建立JavaScript的介面:
[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();
- }
- }
給webview添加JavaScript介面:
[html] view plaincopy
- myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
本地JavaScript檔案:
[javascript] view plaincopy
- <input type="button" value="Say hello" onClick="showAndroidToast(‘Hello Android!‘)" />
-
- <script type="text/javascript">
- function showAndroidToast(toast) {
- Android.showToast(toast);
- }
- </script>
整個代碼如下:
[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() {
- // 載入 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 "";
- }
-
- }
運行效果:
Android WebView JavaScript互動