现在我继续在webview中显示条形图,并在下面的代码的帮助下显示条形图。
public class sample extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WebView webview = (WebView)this.findViewById(R.id.webView);
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setBuiltInZoomControls(true);
webview.requestFocusFromTouch();
webview.setWebChromeClient(new WebChromeClient());
webview.setWebViewClient(new WebViewClient()
{
public void onPageFinished(WebView view, String url)
{
String str = "john";
webview.loadUrl("javascript:callFromActivity('"+str+"')");
}
}
);
webview.loadUrl("file:///android_asset/mypage.html");
}
}
实际上我需要将某些值从Android传递给javaScript 并在图表中显示这些值(例如:在条形图中,我需要在图表中显示不同的用户名,我从Android类到js获得这些值)。 以下链接将值从Android传递给js:http://android-er.blogspot.in/2011/10/call-javascript-inside-webview-from.html
js file:
<html>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
var name=null;
function callFromActivity(s) {
name = document.getElementById("mytext").innerHTML = s;
alert(name);
}
google.load('visualization', '1.1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawStacked);
function drawStacked() {
alert(name);
console.log(name);
var data = google.visualization.arrayToDataTable([
['USER', 'NAME', 'COUNT', 'POSITION'],
['USER1', name, 1, 1],
['USER2', name, 1, 2]
]);
var options = {
is3D: true, title: 'INVOICE',
width: 1200,
height: 240,
legend: { position: 'top'},
bar: { groupWidth: '50%' },
isStacked: true,
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<body >
<div id="chart_div"></div>
<p id="mytext">Hello!</p>
</body>
</html>
我的问题:
callFromActivity函数获取值但是如果我将它传递给drawStacked则显示为未定义。
如果有任何替代方案如何解决这个问题请帮我解决这个问题。
答案 0 :(得分:1)
您在网络视图中注册了一个JS界面。这个
是JS接口的一个例子 public class JsExampleInterface
{
private Context mContext;
public JsExampleInterface(Context context)
{
this.mContext = context;
}
/**
* Returns all the Device info
* @return DeviceInfo object
*/
@JavascriptInterface
public String getDeviceInfo()
{
DeviceInfo deviceInfo = new DeviceInfo();
deviceInfo.setSdk(Build.VERSION.SDK_INT);
deviceInfo.setDevice(Build.DEVICE);
deviceInfo.setModel(Build.MODEL);
deviceInfo.setProduct(Build.PRODUCT);
deviceInfo.setManufacturer(Build.MANUFACTURER);
return mGson.toJson(deviceInfo);
}
}
然后进入 onCreate 方法,您必须像这样注册此界面
JsExampleInterface exampleInterface = new JsExampleInterface(this);
mWebView.addJavascriptInterface(exampleInterface, "ExampleInterface");
之后,您将能够将此js界面用于html,如下所示:
// This returns a JSON object with all device info
ExampleInterface.getDeviceInfo()