WebView的使用

来源:互联网 发布:淘宝买家留言怎么修改 编辑:程序博客网 时间:2024/04/30 12:30

基于慕课网WebView课程教学笔记

在XML中加载布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <WebView        android:id="@+id/webView"        android:layout_width="match_parent"        android:layout_height="match_parent" /></LinearLayout>

调用系统浏览器打开网页

         Uri uri = Uri.parse(url); //url为你要链接的地址 Intent intent =new Intent(Intent.ACTION_VIEW, uri); startActivity(intent);

打开本地资源 网络资源

        webView = (WebView) findViewById(R.id.webView);//WebView加载本地资源webView.loadUrl("file:///android_asset/example.html");//WebView加载web资源webView.loadUrl(url);

在该应用中打开网页

重写shouldOverrideUrlLoading的返回值

// 覆盖WebView默认通过第三方或者是系统浏览器打开网页的行为,使得网页可以在WebVIew中打开webView.setWebViewClient(new WebViewClient(){@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {// TODO Auto-generated method stub//返回值是true的时候控制网页在WebView中去打开,如果为false调用系统浏览器或第三方浏览器去打开view.loadUrl(url);return true;}//WebViewClient帮助WebView去处理一些页面控制和请求通知});

打开JS页面

使其支持JS

  WebSettings settings = webView.getSettings();  settings.setJavaScriptEnabled(true);

WebView加载页面优先使用缓存加载并使用Dialog

settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);webView.setWebChromeClient(new WebChromeClient(){@Overridepublic void onProgressChanged(WebView view, int newProgress) {// TODO Auto-generated method stub                //newProgress 1-100之间的整数if(newProgress==100){//网页加载完毕,关闭ProgressDialogcloseDialog();}else{//网页正在加载,打开ProgressDialogopenDialog(newProgress);}}
private void closeDialog() {// TODO Auto-generated method stub                  if(dialog!=null&&dialog.isShowing())                  {                     dialog.dismiss();                     dialog=null;                  }}private void openDialog(int newProgress) {// TODO Auto-generated method stubif(dialog==null){dialog=new ProgressDialog(MainActivity.this);dialog.setTitle("正在加载");dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);dialog.setProgress(newProgress);dialog.show();}else{dialog.setProgress(newProgress);}}

添加返回事件

//改写物理按键——返回的逻辑@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {// TODO Auto-generated method stubif(keyCode==KeyEvent.KEYCODE_BACK){//Toast.makeText(this, webView.getUrl(), Toast.LENGTH_SHORT).show();if(webView.canGoBack()){webView.goBack();//返回上一页面return true;}else{System.exit(0);//退出程序}}return super.onKeyDown(keyCode, event);}









0 0
原创粉丝点击