就是这么简单。尝试以下
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.WebView;
public class StackOverFlowActivity extends Activity {
private Handler mHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView view=(WebView)findViewById(R.id.webView1);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl("file:///android_asset/index.html");
view.addJavascriptInterface(new MyJavaScriptInterface(), "Android");
}
final class MyJavaScriptInterface
{
public void ProcessJavaScript(final String scriptname, final String args)
{
mHandler.post(new Runnable()
{
public void run()
{
String url="file:///android_asset/img.jpg";
webview.loadUrl("javascript:image(\""+url+"\")");
}
});
}
}
}
索引.html:
<script type="text/javascript">
function getimage()
{
Android.ProcessJavaScript("image",null);
}
function image(src) {
var img = document.createElement("IMG");
img.src = src;
document.getElementById('image').appendChild(img);
}
</script>
并添加以下内容,
<body onload="getimage()" >
要传递更多图像:
function image(src) {
//var img = document.createElement("IMG");
//img.src = src;
// document.getElementById('image').appendChild(img);
images = eval('(' + src+ ')');
for (i = 0; i < images.length; i++) {
var img = document.createElement("IMG");
img.src = images[i];
document.getElementById('image').appendChild(img);
}
}
并且您在加载 url 中传递字符串数组而不是字符串,例如
final class MyJavaScriptInterface
{
public void ProcessJavaScript(final String scriptname, final String args)
{
mHandler.post(new Runnable()
{
public void run()
{
//String url="file:///android_asset/img.jpg";
//webview.loadUrl("javascript:image(\""+url+"\")");
ArrayList<String> url=new ArrayList<String>();
url.add("file:///android_asset/img1.jpg");
url.add("file:///android_asset/img2.jpg");
url.add("file:///android_asset/img3.jpg");
webview.loadUrl("javascript:image(\""+url+"\")");
}
});
}
}
要多次调用图像脚本:
final class MyJavaScriptInterface
{
public void ProcessJavaScript(final String scriptname, final String args)
{
mHandler.post(new Runnable()
{
public void run()
{
// you can load url anywhere in this application. check below to call this inside the other function.
callimageFirstTime(scriptname,args);
// check below to loadurl in other class Test.java
Test newtest=new Test();
newtest.methodtoloadurl(scriptname,args);
}
});
}
}
public void callimageFirstTime(String script, String arguments)
{
// add images with String array and pass here
webview.loadUrl("javascript:image(\""+url+"\")");
}