【问题标题】:How do you call a programmer-defined function in javascript in an android webview?如何在 android webview 中调用 javascript 中的程序员定义函数?
【发布时间】:2015-10-07 22:58:42
【问题描述】:

我已经在一个 html 文件中放置了一个 highchart 仪表并将它加载到一个 webview 中。我创建了一个名为 set_needle() 的函数,将针设置为某个值。但是,当我尝试在 Java 中加载对该函数的 javascript 调用时,什么也没有发生。我查看了几个示例,在我看来它们完全按照我的方式行事,所以我不确定问题出在哪里。

这里是 html/js:

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/highcharts-more.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>

<body>
<div id="container" style="min-width: 310px; max-width: 400px; height: 300px; margin: 0 auto"></div>

<script type="text/javascript">

var needle_value = 0;

function set_value(new_val) {
    needle_value = new_val;
    console.log("setting needle");
}

$(function () {

$('#container').highcharts({

    chart: {
        type: 'gauge',
        plotBackgroundColor: null,
        plotBackgroundImage: null,
        plotBorderWidth: 0,
        plotShadow: false
    },

    title: {
        text: 'Activity Index - Last 24 Hour'
    },

    pane: {
        startAngle: -125,
        endAngle: 125,
        background: [{
            backgroundColor: {
                linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
                stops: [
                    [0, '#FFF'],
                    [1, '#333']
                ]
            },
            borderWidth: 0,
            outerRadius: '109%'
        }, {
            backgroundColor: {
                linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
                stops: [
                    [0, '#333'],
                    [1, '#FFF']
                ]
            },
            borderWidth: 1,
            outerRadius: '107%'
        }, {
            // default background
        }, {
            backgroundColor: '#DDD',
            borderWidth: 0,
            outerRadius: '105%',
            innerRadius: '103%'
        }]
    },

    // the value axis
    yAxis: {
        min: 0,
        max: 200,

        minorTickInterval: 'auto',
        minorTickWidth: 1,
        minorTickLength: 0,
        minorTickPosition: 'inside',
        minorTickColor: '#666',

        tickPixelInterval: 40,
        tickWidth: 1,
        tickPosition: 'inside',
        tickLength: 14,
        tickColor: '#666',
        tickAmount: 11,

        labels: {
            step: 5,
            rotation: 'auto',
            format: '{value}%'
        },
        title: {
            text: 'Activity<br />Index',
            style: {'fontSize':'11px'},
            y: 5
        },
        plotBands: [{
            from: 0,
            to: 60,
            color: '#DF5353' // red
        }, {
            from: 60,
            to: 80,
            color: '#DDDF0D' // yellow
        }, {
            from: 80,
            to: 120,
            color: '#55BF3B' // green
        },
        {
            from: 120,
            to: 140,
            color: '#DDDF0D' // yellow
        },
        {
            from: 140,
            to: 200,
            color: '#DF5353' // red
        }]
    },
    credits: {
        enabled: false
    },
    exporting: {
        enabled: false
    },
    series: [{
        name: 'Activity Index',
        data: [20],
        tooltip: {
            valueSuffix: '% of daily average'
        }
    }]

},
// Add some life
function (chart) {
    if (!chart.renderer.forExport) {
        setInterval(function () {
            var point = chart.series[0].points[0];

            point.update(needle_value);

        }, 3000);
    }
});
});
</script>

这里是相关的java代码:

    WebView myWebView = (WebView) findViewById(R.id.webview);
    myWebView.setWebChromeClient(new WebChromeClient());
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);

    myWebView.loadUrl("file:///android_asset/SleepActivity.html");
    myWebView.loadUrl("javascript:set_value(50)");

【问题讨论】:

    标签: javascript android jquery highcharts android-webview


    【解决方案1】:

    由于您是在 html 页面加载 url 指令之后立即调用 JavaScript 函数,因此尝试执行 JavaScript 时页面可能未完全加载,从而导致错误。
    如果是这种情况我建议推迟自定义WebViewClient的onPageFinished回调上的myWebView.loadUrl("javascript:set_value(50)");指令。比如:

    myWebView.setWebViewClient(new WebViewClient(){
        @Override
        public void onPageFinished(WebView view, String url) {
            view.loadUrl("javascript:set_value(50)");
        }
    });
    

    【讨论】:

      【解决方案2】:

      这是一个示例界面:

      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:

      webView.addJavascriptInterface(new WebAppInterface(this), "Android");
      

      Android 是 javascript 对象的名称,因此您可以像这样从 javascript 中调用它:

      <input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
      
      <script type="text/javascript">
          function showAndroidToast(toast) {
              Android.showToast(toast);
          }
      </script>
      

      @JavascriptInterface 注释很重要;如果没有,则无法从 javascript 调用该方法。

      【讨论】:

        猜你喜欢
        • 2013-06-06
        • 2011-05-18
        • 2016-07-17
        • 2017-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多