我试图在加载到 assets 文件夹中并在 Android 活动中显示在 WebView 中的 xhtml 页面中调用一个简单的 highlight-this-text javascript 函数。使用以下功能:
1.loadUrl("javascript:myFunc(param)");
不工作。
2. 在工作中内联整个函数也不行loadUrl
。
3. 我还尝试在单独的文件(highlighter.js)和 xhtml 正文部分(使用 CDATA 标记)中使用突出显示功能。
上述方法都没有奏效。我需要帮助来弄清楚我做错了什么。
The code:
/* JSWebview:
* 1. Loads a webpage in the external sdcard.
* 2. enables javascript and runs a small script.
*/
package com.sriram.jswebview;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private WebView wv = null;
private String url = null;
private JSInterface myJSI;
private Button fromMain;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadPage();
//wv.loadUrl("javascript:doecho(\"Hello World!\");");
//wv.loadUrl("javascript:tostring());");
String toFind = "Hello";
Log.v(this.toString(), "Finding string = " + toFind);
//find string and highlight.
if(android.os.Build.VERSION.SDK_INT < 16) {
Log.v(this.toString(), "Launching findAll.");
int num = wv.findAll(toFind);
Log.v(this.toString(), num + " instances found.");
} else {
Log.v(this.toString(), "Searching with findAllAsync.");
wv.findAllAsync(toFind);
}
fromMain = (Button) findViewById(R.id.fromMain);
fromMain.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String message = "This is a test.";
wv.loadUrl("javascript:callFromActivity(\""+message+"\")");
//wv.loadUrl("javascript:function (msg) { var oldHTML = document.getElementById(\"highlightbegin\"); var newHTML = \"<span style=\'color:#ffa000\'>\" + msg + \"</span>\"; document.getElementById(\"highlightbegin\").innerHTML = newHTML;}");
}
});
}
@SuppressLint("SetJavaScriptEnabled")
@SuppressWarnings("deprecation")
public void loadPage() {
//loads the index.xhtml page from /mnt/sdcard.
Log.v(this.toString(), "Inside loadPage().");
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//external media is mounted.
url = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "index.xhtml";
Log.v(this.toString(), "URL = " + url);
}
wv = (WebView) findViewById(R.id.wv);
wv.getSettings().setJavaScriptEnabled(true); //enable javascript.
myJSI = new JSInterface(this.getApplicationContext(), wv);
wv.addJavascriptInterface(myJSI, "JSInterface");
if((wv != null) && (url != null)) {
Log.v(this.toString(), "Inside loadurl.");
//wv.loadUrl(url);
wv.loadUrl("file:///android_asset/mypage.xhtml");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
//this class is used to call Javascript functions that act on the html page.
class JSInterface {
private WebView wv = null;
private Context c;
public JSInterface(Context context, WebView w) {
Log.v(this.toString(), "Inside JSInterface constructor.");
c = context;
wv = w;
}
public String tostring() {
//Log.v(this.toString(), "Inside toString()");
String result = "injected Object";
return result;
}
public void doecho(String x) {
Log.v(this.toString(), "Inside doEcho of JSInterface.");
Toast.makeText(wv.getContext(), x, Toast.LENGTH_SHORT).show();
}
public void showToast(String message) {
Toast.makeText(c, message, Toast.LENGTH_LONG).show();
}
public void openAndroidDialog() {
AlertDialog.Builder myDialog = new AlertDialog.Builder(c);
myDialog.setTitle("DANGER!");
myDialog.setMessage("You can do what you want!");
myDialog.setPositiveButton("ON", null);
myDialog.show();
}
}
活动主.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/fromMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="fromMain" />
<WebView
android:id="@+id/wv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_world"
android:layout_above="@id/fromMain" />
</RelativeLayout>
mypage.xhtml(存在于 assets 文件夹中:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta content="application/xhtml+xml;charset=UTF-8" />
<title>My HTML</title>
</head>
<body>
<h1>MyHTML</h1>
<p id="highlightbegin">Hello World! This is a test.</p>
<div> <input type="button" value="Alert" onclick="displayAlert()" /> </div>
<div> <input type="button" value="Say hello" onclick="showAndroidToast('Hello Android!')" /> </div>
<div> <input type="button" value="Open Dialog" onclick="openAndroidDialog()" /> </div>
<div> <input type="button" value="Add highlight" onclick="changeColor()" /> </div>
<script type="text/javascript">
//<![CDATA[
function showAndroidToast(toast) {
JSInterface.showToast(toast);
}
function openAndroidDialog() {
JSInterface.openAndroidDialog();
}
function displayAlert() {
window.alert("I am here!");
}
//]]>
</script>
<script src="doecho.js" type="text/javascript"> </script>
<script src="tostring.js" type="text/javascript"> </script>
<script src="highlighter.js" type="text/javascript"> </script>
</body>
</html>
highlighter.js(包含 javascript 函数):
function callFromActivity(msg) {
alert(msg);
var oldHTML = document.getElementById("highlightbegin");
alert(oldHTML);
var newHTML = "<span style='color:#ffa000'>" + msg + "</span>";
alert(newHTML);
document.getElementById("mytext").innerHTML = newHTML;
}