當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Java调用JavaScript
生活随笔
收集整理的這篇文章主要介紹了
Java调用JavaScript
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1.main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Welcome to Mr Wei's Blog." /> <WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Change the webview content" /> </LinearLayout>2.demo.html
<html> <mce:script language="javascript"><!-- function fillContent(){ document.getElementById("content").innerHTML = "This Content is showed by Android invoke Javascript function."; } // --></mce:script> <body> <p><a onClick="window.demo.startMap()" href="">Start GoogleMap</a></p> <p id="content"></p> <p>A Demo ----Android and Javascript invoke each other.</p> <p>Author:Frankiewei</p> </body> </html>3.WebViewDemo.java
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() {//這里我定義了一個打開地圖應(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()");}});} }
? ? ? ? ? ?
? ? ? ? ? ? ? 首界面 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 點(diǎn)擊按鈕時,html內(nèi)容改變
?
總結(jié)
以上是生活随笔為你收集整理的Java调用JavaScript的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hibernate------java-
- 下一篇: 教练如何引导学员在线报名