kl个人博客 首页>>java>>Android开发之使用WebView打造自己的web app

Android开发之使用WebView打造自己的web app

Android开发之使用WebView打造自己的web app

前言碎语

博主最近想做一款app,因为内容已经有了,故想到了使用WebView来做 ,现将代码贴出如下,供有同样需求的人参考,少走弯路

项目工程地址:https://coding.net/u/kailingchen/p/juanmei_App/git

关键代码如下


public class MainActivity extends Activity{
    private WebView webview;
    private Handler handler;
    private ProgressDialog pd;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initWebView();
    }
    /**
     * 初始化WebView容器
     */
    public void initWebView() {
        //实例化WebView对象
        webview = new WebView(this);
        handler = new Handler() {
            public void handleMessage(Message msg) {//定义一个Handler,用于处理下载线程与UI间通讯
                if (!Thread.currentThread().isInterrupted()) {
                    switch (msg.what) {
                        case 0:
                            pd.show();//显示进度对话框
                            break;
                        case 1:
                            pd.hide();//隐藏进度对话框,不可使用dismiss()、cancel(),否则再次调用show()时,显示的对话框小圆圈不会动。
                            break;
                    }
                }
                super.handleMessage(msg);
            }
        };
        //设置WebViewClient
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;//如果不需要其他对点击链接事件的处理返回true,否则返回false
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                if (!webview.getSettings().getLoadsImagesAutomatically()) {
                    webview.getSettings().setLoadsImagesAutomatically(true);
                }
            }
        });
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int progress) {
                pd.setMessage("数据载入中("+progress+"%),请稍候!");
                if (progress == 100) {
                    handler.sendEmptyMessage(1);//如果全部载入,隐藏进度对话框
                }
                MainActivity.this.setProgress(progress);
            }
        });
        pd = new ProgressDialog(MainActivity.this);
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        handler.sendEmptyMessage(0);
        WebSettings webSettings = webview.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//优先使用缓存的内容
        webSettings.setUseWideViewPort(true);//设定支持网页viewport
        webSettings.setJavaScriptEnabled(true);//设置WebView属性,能够执行Javascript脚本
//        webSettings.setSupportZoom(true);//支持缩放
//        webSettings.setBuiltInZoomControls(true);// 设置显示缩放按钮
//        setZoomControlGone(webview);
        webSettings.supportMultipleWindows();  //多窗口
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//禁止左右滚动
        webview.requestFocusFromTouch();//支持获取手势焦点
        webview.setHorizontalScrollBarEnabled(false);//水平不显示滚动条
        webview.setVerticalScrollbarOverlay(true);
        getWindow().requestFeature(Window.FEATURE_PROGRESS);//设置窗口风格为进度条
        //告诉WebView先不要自动加载图片,等页面finish后再发起图片加载
        if (Build.VERSION.SDK_INT >= 19) {
            webview.getSettings().setLoadsImagesAutomatically(true);
        } else {
            webview.getSettings().setLoadsImagesAutomatically(false);
        }
        //加载需要显示的网页
        webview.loadUrl("http://www.kailing.pub/juanmei/");

        //设置Web视图
        setContentView(webview);
    }
    //实现放大缩小控件隐藏
    public void setZoomControlGone(View view) {
        Class classType;
        Field field;
        try {
            classType = WebView.class;
            field = classType.getDeclaredField("mZoomButtonsController");
            field.setAccessible(true);
            ZoomButtonsController mZoomButtonsController = new ZoomButtonsController(view);
            mZoomButtonsController.getZoomControls().setVisibility(View.GONE);
            try {
                field.set(view, mZoomButtonsController);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
    //设置回退
    //覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
            webview.goBack();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            ConfirmExit();//按了返回键,但已经不能返回,则执行退出确认
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 退出确认框
     */
    public void ConfirmExit() {
        AlertDialog.Builder ad = new AlertDialog.Builder(MainActivity.this);
        ad.setTitle("退出");
        ad.setMessage("是否退出娟妹美甲坊?");
        ad.setPositiveButton("是", new DialogInterface.OnClickListener() {//退出按钮
            @Override
            public void onClick(DialogInterface dialog, int i) {
                // TODO Auto-generated method stub
                MainActivity.this.finish();//关闭activity
                System.exit(0);
            }
        });
        ad.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int i) {
                //不退出不用执行任何操作
            }
        });
        ad.show();//显示对话框
    }
    // 继承GestureListener,重写left和right方法,
    private class MyGestureListener extends GestureListener {
        public MyGestureListener(Context context) {
            super(context);
        }
        @Override
        public boolean left() {
            webview.goForward();
            return super.left();
        }
        @Override
        public boolean right() {
            webview.goBack();
            return super.right();
        }
    }
}



kl个人博客