最近写一个应用时,用到了WebView,可是却突然遇到问题了,首次加载的网页在自定义的webView中显示,可是当点击网页中的链接,却提示使用系统中别的浏览器打开。这样可不好,通过 setWebViewClient(new WebViewClient());解决。以下是用到的两个类:
package com.rilintech.activity;
import com.rilintech.huxike_301.R;
import com.rilintech.view.ProgressWebView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
/**
* @Description:WebView界面,带自定义进度条显示
*
*/
public class BaseWebActivity extends Activity {
protected ProgressWebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_baseweb);
mWebView = (ProgressWebView) findViewById(R.id.baseweb_webview);
initData();
}
protected void initData() {
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String url = bundle.getString("url");
if(!TextUtils.isEmpty(url)){
mWebView.loadUrl(url);
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mWebView = null;
}
}
import com.rilintech.huxike_301.R;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
/**
* @Description: 带进度条的WebView
*
*/
@SuppressWarnings("deprecation")
public class ProgressWebView extends WebView {
private ProgressBar progressbar;
public ProgressWebView(Context context, AttributeSet attrs) {
super(context, attrs);
//为WebView设置进度条
progressbar = new ProgressBar(context, null,
android.R.attr.progressBarStyleHorizontal);
progressbar.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
10, 0, 0));
Drawable drawable = context.getResources().getDrawable(R.drawable.progress_bar_states);
progressbar.setProgressDrawable(drawable);
addView(progressbar);
//为WebView设置WebViewClient处理某些操作
setWebViewClient(new WebViewClient());
setWebChromeClient(new WebChromeClient());
getSettings().setJavaScriptEnabled(true);
//是否支持缩放
getSettings().setSupportZoom(true);
getSettings().setBuiltInZoomControls(true);
}
public class WebChromeClient extends android.webkit.WebChromeClient {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
progressbar.setVisibility(GONE);
} else {
if (progressbar.getVisibility() == GONE)
progressbar.setVisibility(VISIBLE);
progressbar.setProgress(newProgress);
}
super.onProgressChanged(view, newProgress);
}
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
LayoutParams lp = (LayoutParams) progressbar.getLayoutParams();
lp.x = l;
lp.y = t;
progressbar.setLayoutParams(lp);
super.onScrollChanged(l, t, oldl, oldt);
}
}