package com.rong.webView;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.graphics.Bitmap;
public class MainActivity extends Activity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//得到WebView对象
webView = (WebView) findViewById(R.id.webView);
//得到WebSettings对象
WebSettings webSettings = webView.getSettings();
//设置是否支持js(javaScript)
webSettings.setJavaScriptEnabled(true);
//打开webView自带的缩放按钮
webSettings.setBuiltInZoomControls(true);
//设置webView加载页面的方法
setWebView();
}
private long exetime;
//设置返回键为回退
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
/*if(keyCode==KeyEvent.KEYCODE_BACK&&webView.canGoBack()){
webView.goBack();
return true;
}*/
//再按一次就退出
if(System.currentTimeMillis()-exetime>2000){
Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
exetime=System.currentTimeMillis();
}else{
System.exit(0);
}
return true;
}
/**
*
* @param v
*
* 点击加载网页
*/
public void alert(View v){
//访问assets文件夹中的html页面
webView.loadUrl("file:///android_asset/jstest.html");
//设置浏览器的处理类
webView.setWebChromeClient(new WebChromeClient(){
@Override
public boolean onJsAlert(WebView view, String url, String message,
final JsResult result) {
AlertDialog.Builder builder=new Builder(MainActivity.this);
builder.setMessage(message);
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
builder.setNegativeButton("关闭", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
return true;
}
});
}
/**
* 设置webView加载页面的方法
*
*/
private void setWebView() {
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//返回值为false时,当前url交给当前webView处理
return super.shouldOverrideUrlLoading(view, url);
}
//开始加载页面
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
//完成页面加载
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
});
}
}
WebView--(双击退出)
最新推荐文章于 2024-04-05 17:49:48 发布