如何让javascript调用android中的函数?
Android代码
点击(此处)折叠或打开
-
package com.macernow.djstava;
-
-
import android.support.v7.app.ActionBarActivity;
-
import android.os.Bundle;
-
import android.util.Log;
-
import android.view.Menu;
-
import android.view.MenuItem;
-
import android.webkit.JavascriptInterface;
-
import android.webkit.WebView;
-
-
-
public class MainActivity extends ActionBarActivity {
-
-
private static final String TAG = "MainActivity";
-
private WebView webView;
-
-
@Override
-
protected void onCreate(Bundle savedInstanceState) {
-
super.onCreate(savedInstanceState);
-
setContentView(R.layout.activity_main);
-
-
webView = (WebView)findViewById(R.id.webView);
-
webView.getSettings().setJavaScriptEnabled(true);
-
webView.addJavascriptInterface(this,"djstava");
-
webView.loadUrl("http://192.168.31.109/demo.html");
-
-
}
-
-
@JavascriptInterface
-
public void jsextent() {
-
Log.e(TAG,"========== js extension success.");
-
}
-
-
@Override
-
public boolean onCreateOptionsMenu(Menu menu) {
-
// Inflate the menu; this adds items to the action bar if it is present.
-
getMenuInflater().inflate(R.menu.menu_main, menu);
-
return true;
-
}
-
-
@Override
-
public boolean onOptionsItemSelected(MenuItem item) {
-
// Handle action bar item clicks here. The action bar will
-
// automatically handle clicks on the Home/Up button, so long
-
// as you specify a parent activity in AndroidManifest.xml.
-
int id = item.getItemId();
-
-
//noinspection SimplifiableIfStatement
-
if (id == R.id.action_settings) {
-
return true;
-
}
-
-
return super.onOptionsItemSelected(item);
-
}
- }
布局文件
点击(此处)折叠或打开
-
<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:paddingLeft="@dimen/activity_horizontal_margin"
-
android:paddingRight="@dimen/activity_horizontal_margin"
-
android:paddingTop="@dimen/activity_vertical_margin"
-
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
-
-
<WebView
-
android:id="@+id/webView"
-
android:layout_width="fill_parent"
-
android:layout_height="fill_parent">
-
</WebView>
- </RelativeLayout>
测试调用
在javascript脚本中调用java方法
点击(此处)折叠或打开
- window.djstava.jsextent()
扫描关注微信公众号
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。