webview加载html文件,如何调用原生态的代码的

来源:互联网 发布:08 经济危机 知乎 编辑:程序博客网 时间:2024/06/09 23:27

主要调用myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");方法,创建一个节点(本例中创建的android节点);

html文件用通过onclick去调用节点中的方法,

重要部分代码已经标为红色字体了。



代码如下:

public class InterfaceActivity extends Activity {
WebView myWebView;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_interface);


   
myWebView= (WebView)findViewById(R.id.Interface);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<head>");
sb.append("<title>欢迎你</title>");
sb.append("</head>");
sb.append("<body>");
sb.append("<h2>欢迎你访问<a href=\"http://www.crazyit.org\">"+"疯狂Java联盟</a></h2>");
sb.append("            <input type=\"button\" value=\"Say hello\" onClick=\"showAndroidToast('Hello Android11111111111111111111111!')\" /><script type=\"text/javascript\">function showAndroidToast(toast) { Android.showToast(toast);}</script>");
sb.append("</body>");
sb.append("</html>");




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

myWebView.loadDataWithBaseURL(null,sb.toString(), "text/html", "utf-8", null);
}


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();
}
}
}

0 0