- 程序逻辑就是当我点击按钮的时候,webView去访问百度的首页,并且展示出来
- 同时会有网页加载进度的进图条实时显示进度
网页能够回退之前访问的网页
布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
tools:context="com.lingzhuo.testwebview01.MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="访问网路"
android:id="@+id/button" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:id="@+id/progressBar" />
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView" />
</LinearLayout>
- 活动中的代码如下
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button;
private WebView webView;
private ProgressBar progressBar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
button = (Button) findViewById(R.id.button);
webView = (WebView) findViewById(R.id.webView);
button.setOnClickListener(this);
webView.setOnClickListener(this);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
viewWeb();
break;
case R.id.webView:
break;
}
}
private void viewWeb() {
webView.loadUrl("http://www.baidu.com");
//让我们的webView支持java脚本
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//根据传入的参数再去打开新的网页
view.loadUrl(url);
//每次加载新的网页,都将进度条重新显示出来
progressBar.setVisibility(View.VISIBLE);
//表示当前的webView可以处理打开新网页的请求,不用借助系统浏览器
return true;
}
});
//设置网页加载的进度条的显示
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
if (newProgress == 100) {
progressBar.setVisibility(View.GONE);
} else {
progressBar.setProgress(newProgress);
}
}
});
}
//对返回按键进行判断,同时判断webView是否有可以回退的网页,若有,就返回上一个你浏览过的网页
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
- 最后不能忘记要给我们的程序添加访问网络的权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>