WebView (Basic information)

Source: Internet
Author: User

WebView (Basic information)

2014-12-05 09:57:52| Publisher: Android_zero| browse (377)  | Comments (0)

In the design of WebView , not everything should be WebView class dry, some chores are assigned to other people, so WebView concentrate on doing their own analysis, rendering work on the line. Webviewclient is to help WebView handle all kinds of notifications, request events, Webchromeclient is auxiliary WebView Processing JavaScript dialog box, website icon, website title, Loading progress, and so on.

You need to add the following permissions in Androidmanifest.xml when using WebView , otherwise the Web page not available error will occur. :

<uses-permission android:name= "Android.permission.INTERNET"/> <uses-permission android:name= " Android.permission.ACCESS_NETWORK_STATE "/> (some even add this permission)

Set WebView basic information:

Mwebview.getsettings (). Setjavascriptenabled (true);//settings Support JavaScript requestfocus ();//If not set, when you click on the text input box of the Web page, You cannot eject the soft keyboard and do not respond to some other events.  This.setscrollbarstyle (Scrollbars_outside_overlay); Mwebview.loadurl ("http://www.google.com"); Internet with Mwebview.loadurl ("file:///android_asset/XX.html");//local files are stored in: Assets file with local files
First, basic usage1. Set the Zoom page adaptive
Ws.setsupportzoom (TRUE); Support Zoom//ws.setdefaultzoom (WebSettings.ZoomDensity.FAR);   Ws.setbuiltinzoomcontrols (TRUE); Page Auto Adapter Ws.setusewideviewport (TRUE); Ws.setloadwithoverviewmode (TRUE);
2. Jump in Page

WebView Add an event Monitor & Listen object (webviewclient) and override some of these methods shouldoverrideurlloading: Responses to hyperlink buttons in a Web page. When a connection is pressed, Webviewclient calls this method and passes the parameter: the URL that is pressed.

Mwebview.setwebviewclient (New Webviewclient () {@Override public boolean shouldoverrideurlloading (WebView view, String URL) {//Override this method to indicate that clicking on a link in a webpage or jumping in the current webview does not jump to the browser view.loadurl (URL); return true;}
3. Loading progress
This method can handle webview at load time and when loading is complete mwebview.setwebchromeclient (new Webchromeclient () {@Override public void Onprogresschanged (WebView view, int newprogress) {if (newprogress==100) {//Here is the title of the activity, or you can do some other things according to your own needs. Title.settext ("Load Complete");}else{title.settext ("Loading ...");}});
4. Error handling5. Get the website icon

Refer to StackOverflow.

First set the path of the icon store in the OnCreate () method Webicondatabase.getinstance (). Open (Getdir ("Icons", mode_private). GetPath ());   Then set the WebView webchromeclient mwebview.setwebchromeclient (New Mywebchromeclient ()); The following method is overridden in the last mywebchromeclient @Override public void Onreceivedicon (WebView view, Bitmap icon) {if (icon! = null) {miconimg Eview.setimagebitmap (icon); } }
6. Handling the Back key

If you use the webview point link to see a lot of pages later, if you do not do any processing, click the System "back" button, the entire browser will call finish () and end itself, if you want to browse the page fallback instead of exiting the browser, The back event needs to be processed and consumed in the current activity. Overrides the onkeydown (int keycoder,keyevent event) method of the Activity class.

public boolean onKeyDown (int keycoder,keyevent event) {if (Webview.cangoback () && Keycoder = = Keyevent.keycode_ back) {webview.goback ();//goback () returns the previous page of WebView return true;} return false; }
7. Using cache
Webview.getsettings (). Setcachemode (websettings.load_cache_else_network);//First Use cache// Webview.getsettings (). Setcachemode (Websettings.load_no_cache);//delete cache when not using cache//exit, can be placed in the Ondestory () method File File = cache Manager.getcachefilebasedir (); if (file!) = null && file.exists () && file.isdirectory ()) {for (file Item:file.listFiles ()) {Item.delete ();} fil E.delete ();} Mwebview.clearcache (True); Context.deletedatabase ("webview.db"); Context.deletedatabase ("webviewcache.db");
Second, the difficult point1, long press processing
/** *  handles long Press popup context menu events, including web links, image links, etc. ... */ class hao123contextmenulistener  implements oncreatecontextmenulistener{  @Override  public void oncreatecontextmenu ( Contextmenu menu, view v,contextmenuinfo menuinfo)  { hittestresult result  =  ((WebView) v). Gethittestresult ()  ; if (Null == result)  return ;    int type = result.gettype (); if  (type ==  WebView.HitTestResult.UNKNOWN_TYPE)  return;   if  (type ==  WebView.HitTestResult.EDIT_TEXT_TYPE)  { // let TextView handles context  Menu return; }   menuinflater inflater = getactivity (). GetMenuInflater ();  inflater.inflate (r.menu.browser_menu, menu);    // show the correct  menu group string extra = result.gEtextra ();  menu.setgroupvisible (r.id.phone_menu,   type ==  WebView.HitTestResult.PHONE_TYPE);  menu.setgroupvisible (r.id.email_menu,   type ==  webview.hittestresult.email_type);  menu.setgroupvisible (r.id.geo_menu,   type = = webview.hittestresult.geo_type);  menu.setgroupvisible (r.id.image_menu,   type  == webview.hittestresult.image_type | |  type == webview.hittestresult.src_image_anchor_type);  menu.setgroupvisible (R.id.ANCHOR_ menu,   type == webview.hittestresult.src_anchor_type | |  type == webview.hittestresult.src_image_anchor_type);   // setup  custom handling depending on the type intent intent; switch  (Type )  { case webview.hittestresult.phone_type: //processing dial-up  break; case  WebView.HitTestResult.EMAIL_Type: //processing email break; case webview.hittestresult.geo_type: //todo break;  Case webview.hittestresult.src_anchor_type: case webview.hittestresult.src_image_anchor_type:  case WebView.HitTestResult.IMAGE_TYPE: //  Handling Long-Press picture menu items   break; default:  break; } }   private onmenuitemclicklistener menuitemlistener =  new onmenuitemclicklistener ()  {  @Override  public boolean onmenuitemclick ( Menuitem item)  { // TODO  menu item event handling   } };   }
2. Play Flash

1, determine whether the installation of Flash, if not jump to the market installation http://blog.csdn.net/zircon_1973/article/details/8067041

2, the code is set to support flash playback

WebSettings ws = Mwebview.getsettings (); Ws.setjavascriptenabled (TRUE); Ws.setpluginsenabled (TRUE); Flash Support if (Deviceinfo.getsdkversionnumber () >7) {//flash support since Android 2.2 Ws.setpluginstate ( Pluginstate.on); Ws.setallowfileaccess (TRUE); }

The corresponding activity in the androidmanifest is added to the following code:

Android:name= ". Browseractivity "... android:hardwareaccelerated=" "true" .... >.
3, achieve click to download
Mwebview.setdownloadlistener (New Downloadlistener () {public void Ondownloadstart (string url, string useragent,string Contentdisposition, String Mimetype,long contentlength) {//Implement downloaded code, jump to other browser download uri uri = uri.parse (URL);//URI uri = Ur I.parse ("http://www.abc.com/a.apk"), if only a single file is downloaded Intent Intent = new Intent (Intent.action_view,uri); StartActivity (Intent); } });
4. Cookie Preservation

http://blog.csdn.net/jdsjlzx/article/details/7761333

5. Support video Playback

You can refer to this project

6. Handling JS EventsThird, difficult diseases1. Blank Bottom

Vertical scroll bar always shows white track basemap (cannot be eliminated) set a property in the XML for the WebView it doesn't work:

Android:fadescrollbars = "true" Android:scrollbarstyle = "Outsideoverlay" Android:scrollbaralwaysdrawverticaltrack = " False

The WebView must be set in your code to be effective:

WebView. setscrollbarfadingenabled (True); WebView. Setscrollbarstyle (View. Scrollbars_inside_overlay);
2, Uncaught TypeError
E/web Console (804): uncaught typeerror:cannot Call method ' GetItem ' of NULL at HTTP://Z.CDN.TURNER.COM/CNN/TMPL_ASSET/ST Atic/mobile_phone/2273/js/global-min.js:3

Add the following sentence:

WebSettings settings = Webview.getsettings (); Settings.setdomstorageenabled (TRUE);
Iv. Analysis of WebKit

1, Http://mogoweb.net/categories/webkit-research


WebView (Basic information)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.