前提:<uses-permission android:name="android.permission.INTERNET" />
布局文件代码:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/web"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Activity代码
1、加载url
String path ="https://www.baidu.com/";
mWebView.loadUrl(path);
2、设置支持JavaScript
WebSettings settings =mWebView.getSettings();
settings.setJavaScriptEnabled(true);
3、判断WebView是否能返回上一页
重写方法onKeyDown
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK &&mWebView.canGoBack()){
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
或者重写方法
@Override
public void onBackPressed() {
if(mWebView.canGoBack()){
mWebView.goBack();
return;
}
super.onBackPressed();
}
4、设置加载进度条
布局中添加
<ProgressBar
android:id="@+id/progress"
android:layout_width="match_parent"
android:layout_height="10dp"
android:max="100"
android:progress="0"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"/>
mWebView.setWebChromeClient(new WebChromeClient(){
@Override
public void onProgressChanged(WebView view,int newProgress) {
mProgressBar.setProgress(newProgress);
super.onProgressChanged(view, newProgress);
}
});
mWebView.setWebViewClient(new WebViewClient(){
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
mProgressBar.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
mProgressBar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
});
5、获取title
mWebView.setWebChromeClient(new WebChromeClient(){
@Override
public void onReceivedTitle(WebView view, String title) {
setTitle(title);
super.onReceivedTitle(view, title);
}
});
网友评论