Call Javascript function from Android Activity cla

2020-04-23 05:20发布

I am working on application where I need call Javascript function with parameter. For demonstration I write here my code of my Activity from which I want to call js function.

MainActivity:

WebView wView;
FloatingActionButton fab;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    context = this;

    wView = (WebView)findViewById(R.id.webView);

    wView.loadUrl("file:////android_asset/web/index.html");
    wView.getSettings().setJavaScriptEnabled(true);

    fab = (FloatingActionButton ) findViewById(R.id.fab);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            wView.loadUrl("javascript:onClick('say hello world')");
        }
    });
}

My code structure in project: enter image description here

Function which I need to call is into index.js file like this:

function onClick (test) {
alert(test);
}

Html code:

<!doctype html>
<html lang="en">
<head>
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" href="https://openlayers.org/en/v4.0.1/css/ol.css" type="text/css">
    <link rel="stylesheet" href="css/main.css" type="text/css">
    <script src="ol/build/ol.js" type="text/javascript"></script>
    <script src="js/index.js" type="text/javascript"></script>
</head>
<body>
<div id="map" class="full-map"></div>
</body>
</html>

When I press my fab button nothing happened. Any idea how to fix it? Thanks

EDIT:

I also tried add this line into MainActivity:

wView.setWebChromeClient(new WebChromeClient());

but result of this was: enter image description here

0条回答
登录 后发表回答