activrty:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView webView;
private AppCompatActivity activity = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) this.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true); // 设置支持javascript
webView.getSettings().setSupportZoom(true); // 设置支持缩放
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
Log.i("mytag", progress + "");
//System.out.println(progress);
if (progress == 100) {
activity.setTitle(R.string.app_name);
}
}
});
webView.loadUrl("http://www.baidu.com"); //设置webview的url
webView.setWebViewClient(new WebViewClient()); // 设置webViewClient,不写这句会在浏览器中打开
}
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.shidaping.jsbridge.MainActivity">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"></WebView>
</RelativeLayout>
调用webView.getSettings.setJavaScriptEnabled(true)来支持javascript
调用setWebChromeClient方法
可以重写WebChromeClient的onProgressChanged方法来监听网页加载进度的改变。WebChromeClient中可重写的方法还有:
onReceivedTitle:获取网页标题
onReceivedIcon: 获取网页图标
onCloseWindow: 关闭WebView
onJsAlert
onJsPrompt
onjsConfirm
更多方法可直接查看java源码
调用setWebViewClient方法
不调用此方法的话,会在新的浏览器窗口中打开url,而不是activity内
WebViewClient可重写的方法有:
onReceiveError
onPageStart
onPageEnd
等