1、添加权限:AndroidManifest.xml中必须使用许可"android.permission.INTERNET",否则会出Web page not available错误。
在Androidmanifest.xml文件中添加
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
2、在要Activity中生成一个WebView组件:WebView webView = new WebView(this);
3、设置WebView基本信息:
如果访问的页面中有Javascript,则webview必须设置支持Javascript。
webview.getSettings().setJavaScriptEnabled(true);
触摸焦点起作用
requestFocus();
取消滚动条
this.setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY);
4、设置WevView要显示的网页:
互联网用:webView.loadUrl("http://android.tgbus.com");
本地文件用:webView.loadUrl(file:///android_asset/xx.html);固定格式
本地文件存放在:assets文件中
5、如果希望点击链接由自己处理,而不是新开Android的系统browser中响应该链接。
给WebView添加一个事件监听对象(WebViewClient)
并重写其中的一些方法
shouldOverrideUrlLoading:对网页中超链接按钮的响应。
当按下某个连接时WebViewClient会调用这个方法,并传递参数:按下的url
onLoadResource
onPageStart
onPageFinish
onReceiveError
onReceivedHttpAuthRequest
6、如果用webview点链接看了很多页以后,如果不做任何处理,点击系统“Back”键,整个浏览器会调用finish()而结束自身,如果希望浏览的网页回退而不是退出浏览器,需要在当前Activity中处理并消费掉该Back事件。
覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法。
public boolean onKeyDown(int keyCoder,KeyEvent event){
if(webView.canGoBack() && keyCoder == KeyEvent.KEYCODE_BACK){
webview.goBack(); //goBack()表示返回webView的上一页面
return true;
}
return false;
}
比较简单了 直接上代码。
<?xml version="1.0" encoding="utf-8"?><resources> <string name="hello">Hello World, MainActivity!</string> <string name="app_name">test_webview</string> <string name="et">请输入网址</string> <string name="btn">GO</string> <string name="forward">前进</string> <string name="back">后退</string></resources>
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" > <Button android:id="@+id/btnForward" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/forward"/> <Button android:id="@+id/btnBack" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/back"/> <EditText android:id="@+id/et" android:layout_width="175px" android:singleLine="true" android:selectAllOnFocus="true" android:layout_height="wrap_content" android:text="@string/et"/> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="@string/btn"/> </LinearLayout> <WebView android:id="@+id/wv" android:layout_width="wrap_content" android:layout_height="fill_parent"/></LinearLayout>
package xiaohang.zhimeng;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.view.Window;import android.webkit.URLUtil;import android.webkit.WebChromeClient;import android.webkit.WebView;import android.webkit.WebViewClient;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity { WebView wv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 设置Activity显示进度条 getWindow().requestFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.main); wv = (WebView) findViewById(R.id.wv); wv.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { // 重写方法 设置Activity的进度条 MainActivity.this.setProgress(newProgress * 100); } }); wv.setWebViewClient(new WebViewClient() { @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // 重写 onReceivedError方法 创建Toast并显示 Toast.makeText(MainActivity.this, "Sorry!" + description, Toast.LENGTH_LONG).show(); } }); Button btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 获得EditText对象 EditText et = (EditText) findViewById(R.id.et); // 获得地址栏输入的网址 String url = et.getText().toString(); // 判断是否是网址 if (URLUtil.isNetworkUrl(url)) { wv.loadUrl(url); } else { Toast.makeText(MainActivity.this, "对不起, 您输入的网址有错误。", Toast.LENGTH_LONG).show(); // 将焦点移动到EditText et.requestFocus(); } } }); // 设置前进按钮 Button btnForward = (Button) findViewById(R.id.btnForward); btnForward.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 判断是否能前进 if (wv.canGoForward()) { // 进行前进跳转 wv.goForward(); } else { Toast.makeText(MainActivity.this, "对不起, 您现在不能前进。", Toast.LENGTH_LONG).show(); } } }); // 设置后退按钮 Button btnBack = (Button) findViewById(R.id.btnBack); btnBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 判断是否能够后退 if (wv.canGoBack()) { // 进行后退跳转 wv.goBack(); } else { Toast.makeText(MainActivity.this, "对不起, 您现在不能后退。", Toast.LENGTH_LONG).show(); } } }); }}
|
public class WebviewActivity extends Activity {
static public final String URL = "url";
String mCurrentURL = "";
ProgressBar progressHorizontal;
private WebView webview;
private String html;
private String surl;//当前网址
private String turl;//当前根目录
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webview = (WebView) findViewById(R.id.webview);
progressHorizontal=new ProgressBar(this);
ProgressDialogHint.Show(WebviewActivity.this, "提示", "网页加载中...");
new MainLoadData().execute("");// 异步更新
}
//异步加载
class MainLoadData extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
// 获取传递过来的数据
Bundle extras = getIntent().getExtras();
String url = extras.getString(URL);
// 加载需要显示的网页
System.out.println(url);
String text = gethtml(url);
if(text==" "){
}else{
String text1 = text.replace("div class=\"userinfo\"",
"div style=\"display:none\"");
String text2 = text1.replace("div class=\"n3\"",
"div style=\"display:none\"");
String text3 = text2.replace("div class=\"menu\"",
"div style=\"display:none\"");
String text4 = text3.replace("div class=\"addfooter\"",
"div style=\"display:none\"");
String text5=text4.replace("div class=\"topbar\"", "div style=\"display:none\"");
String text6=text5.replace("div class=”logo”", "div style=\"display:none\"");
String text7=text6.replace("div class=\"nav5\"", "div style=\"display:none\"");
html=text7;
}
return null;
}
protected void onPostExecute(Void result) {
// 通知界面刷新
// 设置WebView属性,能够执行Javascript脚本
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setSupportZoom(true);
webview.getSettings().setBuiltInZoomControls(true);
webview.setHorizontalScrollBarEnabled(false);
webview.setVerticalScrollBarEnabled(false);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int mDensity = metrics.densityDpi;
if (mDensity == 240) { // 可以让不同的density的情况下,可以让页面进行适配
webview.getSettings().setDefaultZoom(ZoomDensity.FAR);
} else if (mDensity == 160) {
webview.getSettings().setDefaultZoom(ZoomDensity.MEDIUM);
} else if (mDensity == 120) {
webview.getSettings().setDefaultZoom(ZoomDensity.CLOSE);
}
webview.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
// 设置Web视图
webview.setWebViewClient(webViewClient);
ProgressDialogHint.Dismiss();
}
}
// 获取网页源码内容
private String gethtml(String surl) {
URL url;
try {
url = new URL(surl);
HttpURLConnection connection;
try {
connection = (HttpURLConnection) url.openConnection();
// 设置请求方式为GET方式,就是相当于浏览器打开百度网页
try {
connection.setRequestMethod("GET");
connection.setReadTimeout(35000);
InputStream inStream;
try {
inStream = connection.getInputStream();
ByteArrayOutputStream data = new ByteArrayOutputStream();// 新建一字节数组输出流
byte[] buffer = new byte[1024];// 在内存中开辟一段缓冲区,接受网络输入流
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
data.write(buffer, 0, len);// 缓冲区满了之后将缓冲区的内容写到输出流
}
inStream.close();
String html = new String(data.toByteArray(), "utf-8");
return html;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ProtocolException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}
// Web视图
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
// this表示当前界面,hint是所输入的参数,Toast.LENGTH_SHORT表示边框
private void ToastHint(String hint) {
Toast.makeText(this, hint, Toast.LENGTH_SHORT).show();
}
// 自定义web视图
private WebViewClient webViewClient = new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.contains("?keyword=")||url.contains("http://wap.12582.cn")){
surl=url;
turl=null;
}else{
String i = "http://wap.wxcitycq.com/X9e6463e8dc2afe3f89b526608b70010/0/0/2/023/"
+ url;
surl=i;
turl="http://218.206.27.194/077f7443b41218089d24ccf92917aa93/280/0/2/023/index.php?module=Page&func=Convenience&op=Baike";
}
System.out.println(surl);
String html = gethtml(surl);
if (html == null) {
ToastHint("网页不可链接,报503");
} else {
String text = html.replace("div class=\"userinfo\"",
"div style=\"display:none\"");
String text1 = text.replace("div class=\"n3\"",
"div style=\"display:none\"");
String text2 = text1.replace("div class=\"menu\"",
"div style=\"display:none\"");
String text3 = text2.replace("div class=\"footer\"",
"div style=\"display:none\"");
String text4 = text3.replace("div class=\"t13 subbg\"",
"div style=\"display:none\"");
String text5 = text4.replace("div class=\"thrdheight\"",
"div style=\"display:none\"");
String text6 = text5.replace("div class=\"sobar\"",
"div style=\"display:none\"");
String text7 = text6.replace("<div class=\"firstsubheight\">",
"");
String text8 = text7.replace("div class=\"addfooter\"",
"div style=\"display:none\"");
String text9=text8.replace("div class=”logo”","div style=\"display:none\"");
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_NORMAL);
webview.loadDataWithBaseURL(turl, text9, "text/html", "utf-8",
surl);
}
// view.loadUrl(i);
return true;
}
@Override public void onPageStarted(WebView view, String url,
Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
webview.scrollTo(0, 0);
progressHorizontal.setProgress(5);
progressHorizontal.setVisibility(View.VISIBLE);
mCurrentURL = url;
}
@Override public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
webview.scrollTo(0, 0);
progressHorizontal.setProgress(100);
//mBottomMenuAdapter.SetButtonStopEnable(false);
progressHorizontal.setVisibility(View.GONE);
}
@Override public void onLoadResource(WebView view, String url)
{
super.onLoadResource(view, url);
}
};
@Override
//设置回退
//覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
public boolean onKeyDown(int keyCode, KeyEvent event) {
int d= keyCode;
boolean t= webview.canGoBack();
System.out.println(t);
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
// webview.goBack(); //goBack()表示返回WebView的上一页面
if (html == null) {
ToastHint("网页不可链接,报503");
} else {
String text = html.replace("div class=\"userinfo\"",
"div style=\"display:none\"");
String text1 = text.replace("div class=\"n3\"",
"div style=\"display:none\"");
String text2 = text1.replace("div class=\"menu\"",
"div style=\"display:none\"");
String text3 = text2.replace("div class=\"footer\"",
"div style=\"display:none\"");
String text4 = text3.replace("div class=\"t13 subbg\"",
"div style=\"display:none\"");
String text5 = text4.replace("div class=\"thrdheight\"",
"div style=\"display:none\"");
String text6 = text5.replace("div class=\"sobar\"",
"div style=\"display:none\"");
String text7 = text6.replace("<div class=\"firstsubheight\">",
"");
String text8 = text7.replace("div class=\"addfooter\"",
"div style=\"display:none\"");
String text9=text8.replace("div class=”logo”","div style=\"display:none\"");
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_NORMAL);
webview.loadDataWithBaseURL(turl, text9, "text/html", "utf-8",
surl);
}
return true;
}else{
onBackPressed();
}
return false;
}
}