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

主要调用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();
}
}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值