参考:http://blog.csdn.net/rodulf/article/details/52109246
有的网站可能通过loadUrl打开的时候是打不开的,例如www.baidu.com在下面的例子中就是打不开的
package com.kodulf.webviewdemo;
import android.inputmethodservice.Keyboard;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
//有两种方法,一种是直接的loadUrl,另一种是加载源码
webView.loadUrl("http://www.qiushibaike.com");//注意了,这里如果输入www.baidu.com的话有可能就打不开了
//如果是上面的直接loadUrl的话,会调用我们系统的浏览器去打开上面的网址,有了下面的webviewclient的设置,会在我们的应用中打开
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
//return super.shouldOverrideUrlLoading(view, url);
return true;
}
});
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.setWebChromeClient(new WebChromeClient(){
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
Log.d("kodulf","当前的进度"+newProgress);
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//return super.onKeyDown(keyCode, event);
if(keyCode== KeyEvent.KEYCODE_BACK){
if(webView.canGoBack()){
webView.goBack();
return true;
}else{
System.exit(0);//推出程序
}
}
return super.onKeyDown(keyCode, event);
}
}
<?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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kodulf.webviewdemo.MainActivity">
<WebView
android:id="@+id/webview"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
</RelativeLayout>
permission
<uses-permission android:name="android.permission.INTERNET"></uses-permission>