WebView的设置

来源:互联网 发布:网络远程监控软件 编辑:程序博客网 时间:2024/06/06 12:03
public class MainActivity extends Activity {


    private WebView wv;
private ProgressBar pb;


@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EditText ed = (EditText) findViewById(R.id.ed);
        pb = (ProgressBar) findViewById(R.id.pb);
        wv = (WebView) findViewById(R.id.wv);
        //给ed设置一个点击回车的监听,这个监听主要是监听编辑框的,还有其他动作,
        ed.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
String path=v.getText().toString().trim();
wv.loadUrl(path);
//这个设置为true,处理完事件后停止往下传递,如果为false的话还会往下传递,
//这里的表现就是如果为true的话,点击回车之后不会换行,因为事件不往下传递了,如果是false的话还会往下传递,就会显示换行
return true;
}
});
        //这个监听是给编辑框添加一个文本改变的监听,监听所输入的文本的
        ed.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String path=s.toString().trim();
if(path.endsWith(".com")||path.endsWith(".html")){
wv.loadUrl(path);
}

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub

}
});
        //设置只在当前界面进行跳转
        wv.setWebViewClient(new WebViewClient());
        insetting();
        //设置浏览客户端对象6
        wv.setWebChromeClient(new WebChromeClient(){


@Override
public void onProgressChanged(WebView view, int newProgress) {
//让pb进行显示
pb.setVisibility(View.VISIBLE);
pb.setProgress(newProgress);
if(newProgress==100){
pb.setVisibility(View.GONE);
}
super.onProgressChanged(view, newProgress);
}
        });
    }
private void insetting() {
//获取web设置器,设置各种属性
WebSettings settings = wv.getSettings();
//设置通过js打开新窗口
settings.setJavaScriptCanOpenWindowsAutomatically(true);
//设置支持js
settings.setJavaScriptEnabled(true);

//
settings.setSupportZoom(true); 
settings.setBuiltInZoomControls(true);
//设置如何缓存 默认使用缓存,当缓存没有,或者缓存过期,使用网络
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
//设置如何缓存 默认使用缓存,即便是缓存过期,也使用缓存 ,只有缓存消失,使用网络
// settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

//使页面可缩放
settings.setUseWideViewPort(true);
//打开页面时,自适应屏幕
settings.setLoadWithOverviewMode(true);
}
//一个键盘的监听,在android中所有的按键都会有一个键盘码,
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//如果当前的键盘码是返回键的键盘码的话
if(keyCode==KeyEvent.KEYCODE_BACK){
//如果wv可以返回的话,也就是说不是第一页,就进行返回,如果不能返回的话就关闭
if(wv.canGoBack()){
wv.goBack();
}else{
finish();
}
}
//返回true表示已经完整的处理了这个时间,并不希望其他回调方法继续对其进行处理,
return true;
}
}
1 0