WebView点击里面的按钮跳转到Activity
工作中遇到的一些东西积累分享
- 怎么通过点击webview里面的按钮跳转到我们自己的Activity
话不多说直接上代码
首先我们来看一下Webview
一、在xml中:
<WebView
android:id="@+id/web"
android:layout_width="match_parent"
android:layout_height="match_parent"></WebView>
二、如何在Webview来实现:
public void initView() {
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
WebSettings wSet = webView.getSettings();
//设置打开Webview 的路径;我这里是在自己的工程中写了一个HTML所以路径是这样写的
webView.loadUrl("file:///android_asset/two.html");
//因为我们这里访问的页面中要与Javascript交互,则webview必须设置支持Javascript
wSet.setJavaScriptEnabled(true);
//最后只需要去调用这个方法
webView.addJavascriptInterface(this, "webview");
}
@JavascriptInterface
public void startActivity(String name, String psd) {
Intent intent = new Intent();
intent.putExtra("name", name);
intent.putExtra("psd", psd);
intent.setClass(this, TestVewActivity.class);
this.startActivity(intent);
}
三、接下来就是在自己的工程目录下写一个Html页面
Html的内容:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript">
function startActivity() {
try{
var str = document.getElementById("name").value
webview.startActivity(str,"psd");
}catch(e){
document.getElementById("ss").innerHTML=e;
}
}
</script>
</head>
<body>
<input id="name" type="button" value="button" ontouchend="startActivity()"/>
</body>
</html>
大工告成!!!!!!!