Android中WebView详解

WebView细节知识整合:

java.lang.Object
   ↳android.view.View
    ↳android.view.ViewGroup
     ↳android.widget.AbsoluteLayout
      ↳android.webkit.WebView

webview可以有孩子。

A View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity.

我们可以创建自己的web浏览器  也可以仅仅在activity里面显示一个web页面。

注意  如果我们仅仅上将webview(html页面)作为我们ui的一部分 这个时候  我们就可以使用webview很好地实现我们的目标,  同时这个时候用户是不可以与web页面交互的。      但是如果我们想实现交互  这个时候  我们就需要建立一个web浏览器     同时我们需要调用一个浏览器应用借助一个url地址,而不是一个webview

第二种情况的例子如下:

Uri uri = Uri.parse("http://www.example.com");
 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
 startActivity(intent);

注意  上面的方式就是通过 一个网址的方式  去访问相关的页面的。

如果你真的想要一个成熟的web浏览器,那么你可能想和一个URL调用浏览器应用程序的意图,而不是显示WebView。


To provide a WebView in your own Activity, include a in your layout, or set the entire Activity window as a WebView duringonCreate():

设置一个webview在你的界面activity里面  我们就需要做下面的操作


小demo如下:


 WebView webview = new WebView(this);
 setContentView(webview);
Then load the desired web page:

webview.loadUrl("http://slashdot.org/");
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
 webview.loadData(summary, "text/html", null);
加载数据的名称   数据的类型

上面的就是一个例子  加载一段html数据      


A WebView has several customization points where you can add your own behavior.

webview有几个设置点   借助这几个设置点 我们可以添加自己的行为。


WebChromeClient

extends Object
java.lang.Object
   ↳android.webkit.WebChromeClient
就是一个回调的接口,通知当前页面的自定义视图已被撤销。

创建和设置WebChromeClient子类。这个类时可能会影响浏览器用户界面发生的事情,例如,进度更新和JavaScript警告发送在这里(参见调试任务)。


创建和设置WebViewClient子类。它将被称为当事情发生,影响呈现的内容,例如,错误或表单提交。你也可以在这里拦截URL加载


Modifying the WebSettings, such as enabling JavaScript withsetJavaScriptEnabled()

修改webSetting

将Java对象注入WebView使用addJavascriptInterface(对象、字符串)方法。这个方法允许您将Java对象注入到一个页面的JavaScript上下文,这样他们可以通过JavaScript访问的页面。



例子:如下

getWindow().requestFeature(Window.FEATURE_PROGRESS);

 webview.getSettings().setJavaScriptEnabled(true);

 final Activity activity = this;





 webview.setWebChromeClient(new WebChromeClient() {
   public void onProgressChanged(WebView view, int progress) {
     // Activities and WebViews measure progress with different scales.
     // The progress meter will automatically disappear when we reach 100%
     activity.setProgress(progress * 1000);
   }
 });



 webview.setWebViewClient(new WebViewClient() {
   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
   }
 });

 webview.loadUrl("http://slashdot.org/");

注意  第二个接口回调  其实现实的就是 我们加载web页面的进度,

第三个接口   就是我们失败的时候  作出的反应。


For obvious security reasons, your application has its own cache,

cookie store etc.—it does not share the Browser application's data.  浏览器应用和他不是同一个存储数据的地方,


构建web页面来支持不同的屏幕密度


Here's a summary of the features you can use to handle different screen densities:


The -webkit-device-pixel-ratio CSS media query. Use this to specify the screen densities for which this style sheet is to be used. The corresponding value should be either "0.75", "1", or "1.5", to indicate that the styles are for devices with low density, medium density, or high density screens, respectively. For example: 


<link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" />

The hdpi.css stylesheet is only used for devices with a screen pixel ration of 1.5, which is the high density pixel ratio.


清空cache内的数据

         public void clearCache(boolean includeDiskFiles)
Added in API level 1

Clears the resource cache. Note that the cache is per-application, so this will clear the cache for all WebViews used.

Parameters
includeDiskFilesif false, only the RAM cache is cleared 


         public int getProgress()
Added in API level 1

Gets the progress for the current page.

Returns
  • the progress for the current page between 0 and 100 

         public WebSettings getSettings ()
Added in API level 1

Gets the WebSettings object used to control the settings for this WebView.

Returns
  • a WebSettings object that can be used to control this WebView's settings 

         public String getTitle ()
Added in API level 1

Gets the title for the current page. This is the title of the current page until WebViewClient.onReceivedTitle is called.

Returns
  • the title for the current page 


         public String getUrl ()
Added in API level 1

Gets the URL for the current page. This is not always the same as the URL passed to WebViewClient.onPageStarted because although the load for that URL has begun, the current page may not have changed.

Returns
  • the URL for the current page 


         public void loadData(String data,String mimeType, String encoding)
Added in API level 1

Loads the given data into this WebView using a 'data' scheme URL.

Note that JavaScript's same origin policy means that script running in a page loaded using this method will be unable to access content loaded using any scheme other than 'data', including 'http(s)'. To avoid this restriction, useloadDataWithBaseURL() with an appropriate base URL.

The encoding parameter specifies whether the data is base64 or URL encoded. If the data is base64 encoded, the value of the encoding parameter must be 'base64'. For all other values of the parameter, including null, it is assumed that the data uses ASCII encoding for octets inside the range of safe URL characters and use the standard %xx hex encoding of URLs for octets outside that range. For example, '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.

The 'data' scheme URL formed by this method uses the default US-ASCII charset. If you need need to set a different charset, you should form a 'data' scheme URL which explicitly specifies a charset parameter in the mediatype portion of the URL and callloadUrl(String) instead. Note that the charset obtained from the mediatype portion of a data URL always overrides that specified in the HTML or XML document itself.

Parameters
dataa String of data in the given encoding
mimeTypethe MIME type of the data, e.g. 'text/html'
encodingthe encoding of the data 


         public void loadUrl(String url)
Added in API level 1

Loads the given URL.

Parameters
urlthe URL of the resource to load 


         public boolean onKeyDown (int keyCode, KeyEvent event)
Added in API level 1

Default implementation of KeyEvent.Callback.onKeyDown(): perform press of the view when KEYCODE_DPAD_CENTER orKEYCODE_ENTER is released, if the view is enabled and clickable.

Key presses in software keyboards will generally NOT trigger this listener, although some may elect to do so in some situations. Do not rely on this to catch software key presses.

Parameters
keyCodeA key code that represents the button pressed, from KeyEvent.
eventThe KeyEvent object that defines the button action.
Returns
  • If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false. 


         public boolean onKeyUp (int keyCode, KeyEvent event)
Added in API level 1

Default implementation of KeyEvent.Callback.onKeyUp(): perform clicking of the view when KEYCODE_DPAD_CENTER orKEYCODE_ENTER is released.

Key presses in software keyboards will generally NOT trigger this listener, although some may elect to do so in some situations. Do not rely on this to catch software key presses.

Parameters
keyCodeA key code that represents the button pressed, from KeyEvent.
eventThe KeyEvent object that defines the button action.
Returns
  • If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false. 


         public boolean onTouchEvent (MotionEvent event)
Added in API level 1

Implement this method to handle touch screen motion events.

Parameters
eventThe motion event.
Returns
  • True if the event was handled, false otherwise. 

         public void onWindowFocusChanged(boolean hasWindowFocus)
Added in API level 1

Called when the window containing this view gains or loses focus. Note that this is separate from view focus: to receive key events, both your view and its window must have focus. If a window is displayed on top of yours that takes input focus, then your own window will lose focus but the view focus will remain unchanged.

Parameters
hasWindowFocusTrue if the window containing this view now has focus, false otherwise. 


         public boolean pageDown (boolean bottom)
Added in API level 1

Scrolls the contents of this WebView down by half the page size.

Parameters
bottomtrue to jump to bottom of page
Returns
  • true if the page was scrolled
public boolean pageUp(boolean top)
Added in API level 1

Scrolls the contents of this WebView up by half the view size.

Parameters
toptrue to jump to the top of the page
Returns
  • true if the page was scrolled 

         public boolean requestFocus (int direction, Rect previouslyFocusedRect)
Added in API level 1

Call this to try to give focus to a specific view or to one of its descendants and give it hints about the direction and a specific rectangle that the focus is coming from. The rectangle can help give larger views a finer grained hint about where focus is coming from, and therefore, where to show selection, or forward focus change internally. A view will not actually take focus if it is not focusable (isFocusable() returns false), or if it is focusable and it is not focusable in touch mode (isFocusableInTouchMode()) while the device is in touch mode. A View will not take focus if it is not visible. A View will not take focus if one of its parents hasgetDescendantFocusability() equal toFOCUS_BLOCK_DESCENDANTS. See alsofocusSearch(int), which is what you call to say that you have focus, and you want your parent to look for the next one. You may wish to override this method if your customView has an internalView that it wishes to forward the request to. Looks for a view to give focus to respecting the setting specified by getDescendantFocusability(). Uses onRequestFocusInDescendants(int, android.graphics.Rect) to find focus within the children of this group when appropriate.

Parameters
directionOne of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
previouslyFocusedRectThe rectangle (in this View's coordinate system) to give a finer grained hint about where focus is coming from. May be null if there is no hint.
Returns
  • Whether this view or one of its descendants actually took focus. 

         public void setBackgroundColor(int color)
Added in API level 1

Sets the background color for this view.

Parameters
colorthe color of the background 

         public void setDownloadListener(DownloadListener listener)
Added in API level 1

Registers the interface to be used when content can not be handled by the rendering engine, and should be downloaded instead. This will replace the current handler.

Parameters
listeneran implementation of DownloadListener 


         public void setLayoutParams(ViewGroup.LayoutParams params)
Added in API level 1

Set the layout parameters associated with this view. These supply parameters to theparent of this view specifying how it should be arranged. There are many subclasses of ViewGroup.LayoutParams, and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children.

Parameters
paramsThe layout parameters for this view, cannot be null 


         public void setPictureListener(WebView.PictureListener listener)
Added in API level 1

This method was deprecated in API level 12.
This method is now obsolete.

Sets the Picture listener. This is an interface used to receive notifications of a new Picture.

Parameters
listeneran implementation of WebView.PictureListener


         public void setWebViewClient(WebViewClient client)
Added in API level 1

Sets the WebViewClient that will receive various notifications and requests. This will replace the current handler.

Parameters
clientan implementation of WebViewClient 


         protected void onFocusChanged (boolean focused, int direction,Rect previouslyFocusedRect)
Added in API level 1

Called by the view system when the focus state of this view changes. When the focus change event is caused by directional navigation, direction and previouslyFocusedRect provide insight into where the focus is coming from. When overriding, be sure to call up through to the super class so that the standard focus handling will occur.

Parameters
focusedTrue if the View has focus; false otherwise.
directionThe direction focus has moved when requestFocus() is called to give this view focus. Values areFOCUS_UP,FOCUS_DOWN,FOCUS_LEFT,FOCUS_RIGHT,FOCUS_FORWARD, orFOCUS_BACKWARD. It may not always apply, in which case use the default.
previouslyFocusedRectThe rectangle, in this view's coordinate system, of the previously focused view. If applicable, this will be passed in as finer grained information about where the focus is coming from (in addition to direction). Will benull otherwise. 


         protected void onOverScrolled (int scrollX, int scrollY, boolean clampedX, boolean clampedY)
Added in API level 9

Called by overScrollBy(int, int, int, int, int, int, int, int, boolean) to respond to the results of an over-scroll operation.

Parameters
scrollXNew X scroll value in pixels
scrollYNew Y scroll value in pixels
clampedXTrue if scrollX was clamped to an over-scroll boundary
clampedYTrue if scrollY was clamped to an over-scroll boundary 



         protected void onScrollChanged (int l, int t, int oldl, int oldt)
Added in API level 1

This is called in response to an internal scroll in this view (i.e., the view scrolled its own contents). This is typically as a result ofscrollBy(int, int) orscrollTo(int, int) having been called.

Parameters
lCurrent horizontal scroll origin.
tCurrent vertical scroll origin.
oldlPrevious horizontal scroll origin.
oldtPrevious vertical scroll origin. 


         protected void onSizeChanged (int w, int h, int ow, int oh)
Added in API level 1

This is called during layout when the size of this view has changed. If you were just added to the view hierarchy, you're called with the old values of 0.

Parameters
wCurrent width of this view.
hCurrent height of this view.
owOld width of this view.
ohOld height of this view. 

        
 protected void onVisibilityChanged(View changedView, int visibility)
Added in API level 8

Called when the visibility of the view or an ancestor of the view is changed.

Parameters
changedViewThe view whose visibility changed. Could be 'this' or an ancestor view.
visibilityThe new visibility of changedView: VISIBLE,INVISIBLE orGONE


websetting

Manages settings state for a WebView. When a WebView is first created, it obtains a set of default settings. These default settings will be returned from any getter call.

我们在创建webview的时候   默认会有一些默认的设置,


WebSettings.TextSize


Use setTextZoom(int) and getTextZoom() instead.    

Enum for specifying the text size.

Enum for specifying the text size.

  • SMALLEST is 50%
  • SMALLER is 75%
  • NORMAL is 100%
  • LARGER is 150%
  • LARGEST is 200%

注意  我们这个地方可以设置   web页面的文字的大小   这个时候  就可以借助这个方法 webview.getSettings().setTextSize(WebSettings.TextSize.LARGEST); 


这个时候   就额可以根据每种类型来设置我们屏幕分辨率下的文字的大小。

注意  我们这个地方借助的是枚举的方法实现的。   枚举获得每个类型的数值。   


WebSettings.ZoomDensity

extends Enum<E extends  Enum<E>>


Enum for specifying the WebView's desired density.

  • FAR makes 100% looking like in 240dpi
  • MEDIUM makes 100% looking like in 160dpi
  • CLOSE makes 100% looking like in 120dpi

LOAD_CACHE_ELSE_NETWORK       Use cached resources when they are available, even if they have expired.


LOAD_CACHE_ONLY     Don't use the network, load from the cache.


 LOAD_DEFAULT
         Default cache usage mode.

LOAD_NORMAL             This constant was deprecated in API level 17. This value is obsolete, as from API level HONEYCOMB and onwards it has the same effect as LOAD_DEFAULT


LOAD_NO_CACHE                         Don't use the cache, load from the network.


         public boolean enableSmoothTransition ()
Added in API level 11

This method was deprecated in API level 17.
This method is now obsolete, and will become a no-op in future.

Gets whether the WebView enables smooth transition while panning or zooming.

设置web页面  是否可以平稳的  移动  缩放。   


public void setAllowContentAccess(boolean allow)
Added in API level 11

Enables or disables content URL access within WebView. Content URL access allows WebView to load content from a content provider installed in the system. The default is enabled. 

启用或禁用在WebView内容URL访问。 内容的URL访问允许WebView加载内容从系统中安装一个内容提供者。 默认是启用的。


         public void setAllowFileAccess(boolean allow)
Added in API level 3

Enables or disables file access within WebView. File access is enabled by default. Note that this enables or disables file system access only. Assets and resources are still accessible using file:///android_asset and file:///android_res. 


WebView中启用或禁用文件访问。 文件访问默认情况下是启用的。 请注意,这仅启用或禁用文件系统访问。 资产和资源仍然可以使用文件:/ / / android_asset和文件:/ / / android_res。


         public abstract void setAllowFileAccessFromFileURLs (boolean flag)
Added in API level 16

Sets whether JavaScript running in the context of a file scheme URL should be allowed to access content from other file scheme URLs. To enable the most restrictive, and therefore secure policy, this setting should be disabled. Note that the value of this setting is ignored if the value of getAllowUniversalAccessFromFileURLs() is true. Note too, that this setting affects only JavaScript access to file scheme resources. Other access to such resources, for example, from image HTML elements, is unaffected.

The default value is true for API level ICE_CREAM_SANDWICH_MR1 and below, and false for API level JELLY_BEAN and above.

Parameters
flagwhether JavaScript running in the context of a file scheme URL should be allowed to access content from other file scheme URLs 

集JavaScript文件的上下文中运行方案是否应该允许URL访问内容从其他文件方案的URL。使最严格,因此安全政策,应禁用此设置。注意,该设置将被忽略的价值如果getAllowUniversalAccessFromFileURLs()是正确的。太注意,此设置只影响JavaScript访问文件计划资源。其他访问这些资源,例如,从图像的HTML元素,不受影响。
API的默认值为true ICE_CREAM_SANDWICH_MR1及以下水平,和假API JELLY_BEAN及以上水平。


         public abstract void setAllowUniversalAccessFromFileURLs (boolean flag)
Added in API level 16

Sets whether JavaScript running in the context of a file scheme URL should be allowed to access content from any origin. This includes access to content from other file scheme URLs. SeesetAllowFileAccessFromFileURLs(boolean). To enable the most restrictive, and therefore secure policy, this setting should be disabled. Note that this setting affects only JavaScript access to file scheme resources. Other access to such resources, for example, from image HTML elements, is unaffected.

The default value is true for API level ICE_CREAM_SANDWICH_MR1 and below, and false for API level JELLY_BEAN and above.

Parameters
flagwhether JavaScript running in the context of a file scheme URL should be allowed to access content from any origin 
集JavaScript文件的上下文中运行方案是否应该允许URL访问内容从任何来源。 这包括从其他文件方案的url访问内容。 看到setAllowFileAccessFromFileURLs(布尔)。 使最严格,因此安全政策,应禁用此设置。 请注意,此设置只影响JavaScript访问文件计划资源。 其他访问这些资源,例如,从图像的HTML元素,不受影响。
API的默认值为true ICE_CREAM_SANDWICH_MR1及以下水平,和假API JELLY_BEAN及以上水平。
API的默认值为true ICE_CREAM_SANDWICH_MR1及以下水平,和假API JELLY_BEAN及以上水平。


         public synchronized voidsetAppCacheEnabled (boolean flag)
Added in API level 7

Sets whether the Application Caches API should be enabled. The default is false. Note that in order for the Application Caches API to be enabled, a valid database path must also be supplied tosetAppCachePath(String).

Parameters
flagtrue if the WebView should enable Application Caches 


         public synchronized voidsetAppCacheMaxSize (long appCacheMaxSize)
Added in API level 7

This method was deprecated in API level 18.
In future quota will be managed automatically.

Sets the maximum size for the Application Cache content. The passed size will be rounded to the nearest value that the database can support, so this should be viewed as a guide, not a hard limit. Setting the size to a value less than current database size does not cause the database to be trimmed. The default size is MAX_VALUE. It is recommended to leave the maximum size set to the default value.

Parameters
appCacheMaxSizethe maximum size in bytes


         public synchronized voidsetAppCachePath (String appCachePath)
Added in API level 7

Sets the path to the Application Caches files. In order for the Application Caches API to be enabled, this method must be called with a path to which the application can write. This method should only be called once: repeated calls are ignored.

Parameters
appCachePatha String path to the directory containing Application Caches files.

         public void setBuiltInZoomControls(boolean enabled)
Added in API level 3

Sets whether the WebView should use its built-in zoom mechanisms. The built-in zoom mechanisms comprise on-screen zoom controls, which are displayed over the WebView's content, and the use of a pinch gesture to control zooming. Whether or not these on-screen controls are displayed can be set with setDisplayZoomControls(boolean). The default is false.

The built-in mechanisms are the only currently supported zoom mechanisms, so it is recommended that this setting is always enabled.

Parameters
enabledwhether the WebView should use its built-in zoom mechanisms 

集webview是否应该使用其内置的放大机制。内置的放大机制包括屏幕缩放控件,显示WebView的内容,和少量的使用手势来控制缩放。这些是否可以设置屏幕显示控制与setDisplayZoomControls(布尔)。默认的是假的。
内置的机制是目前唯一支持放大机制,因此建议此设置总是启用。


         public void setCacheMode(int mode)
Added in API level 1

Overrides the way the cache is used. The way the cache is used is based on the navigation type. For a normal page load, the cache is checked and content is re-validated as needed. When navigating back, content is not revalidated, instead the content is just retrieved from the cache. This method allows the client to override this behavior by specifying one ofLOAD_DEFAULT,LOAD_CACHE_ELSE_NETWORK,LOAD_NO_CACHE orLOAD_CACHE_ONLY. The default value isLOAD_DEFAULT.

Parameters
modethe mode to use 

覆盖的方式使用缓存。使用缓存的方式是基于导航类型。正常页面加载的情况下将缓存检查和内容。当导航,内容不是重新检验它,而不是只是从缓存检索的内容。这种方法允许客户端覆盖此行为通过指定LOAD_DEFAULT之一,LOAD_CACHE_ELSE_NETWORK,LOAD_NO_CACHE或LOAD_CACHE_ONLY。默认值是LOAD_DEFAULT。


         public synchronized voidsetDatabaseEnabled (boolean flag)
Added in API level 5

Sets whether the database storage API is enabled. The default value is false. See alsosetDatabasePath(String) for how to correctly set up the database storage API. This setting is global in effect, across all WebView instances in a process. Note you should only modify this setting prior to makingany WebView page load within a given process, as the WebView implementation may ignore changes to this setting after that point.

Parameters
flagtrue if the WebView should use the database storage API 

设置是否启用数据库存储API。默认值是错误的。参见setDatabasePath(字符串)如何正确设置数据库存储API。这个设置是全球性的,在所有的WebView实例的过程。注意你应该只修改这个设置之前做任何WebView页面加载在一个给定的过程,随着WebView实现可能忽视这一点后更改此设置。


         public synchronized voidsetDatabasePath (String databasePath)
Added in API level 5

Sets the path to where database storage API databases should be saved. In order for the database storage API to function correctly, this method must be called with a path to which the application can write. This method should only be called once: repeated calls are ignored.

Parameters
databasePatha path to the directory where databases should be saved. 

         public synchronized voidsetDefaultFixedFontSize (int size)
Added in API level 1

Sets the default fixed font size. The default is 16.

Parameters
sizea non-negative integer between 1 and 72. Any number outside the specified range will be pinned. 

         public synchronized voidsetDefaultFontSize (int size)
Added in API level 1

Sets the default font size. The default is 16.

Parameters
sizea non-negative integer between 1 and 72. Any number outside the specified range will be pinned. 

设置默认字体大小。缺省值是16。


         public synchronized voidsetDefaultTextEncodingName (String encoding)
Added in API level 1

Sets the default text encoding name to use when decoding html pages. The default is "Latin-1".

Parameters
encodingthe text encoding name 

         public void setDefaultZoom(WebSettings.ZoomDensity zoom)
Added in API level 7

Sets the default zoom density of the page. This must be called from the UI thread. The default isMEDIUM.

Parameters
zoomthe zoom density 

设置默认页面的缩放密度。这必须从UI线程调用。默认是媒介。


         public void setDisplayZoomControls(boolean enabled)
Added in API level 11

Sets whether the WebView should display on-screen zoom controls when using the built-in zoom mechanisms. SeesetBuiltInZoomControls(boolean). The default is true.

Parameters
enabledwhether the WebView should display on-screen zoom controls 

集WebView是否应该显示屏幕缩放控件当使用内置的放大机制。看到setBuiltInZoomControls(布尔)。默认是正确的。


   

         public synchronized voidsetDomStorageEnabled (boolean flag)
Added in API level 7

Sets whether the DOM storage API is enabled. The default value is false.

Parameters
flagtrue if the WebView should use the DOM storage API 


设置是否启用了DOM storage API。默认值是错误的。



         public void setEnableSmoothTransition(boolean enable)
Added in API level 11

This method was deprecated in API level 17.
This method is now obsolete, and will become a no-op in future.

Sets whether the WebView will enable smooth transition while panning or zooming or while the window hosting the WebView does not have focus. If it is true, WebView will choose a solution to maximize the performance. e.g. the WebView's content may not be updated during the transition. If it is false, WebView will keep its fidelity. The default value is false.

集WebView能否实现平稳过渡而平移或缩放或同时承载WebView没有焦点的窗口。 如果这是真的,WebView将选择一个解决方案来最大化性能。 例如WebView的内容可能不是在过渡更新。 如果它是假的,WebView将保持忠诚。 默认值是错误的。


         public synchronized voidsetFantasyFontFamily (String font)
Added in API level 1

Sets the fantasy font family name. The default is "fantasy".

Parameters
fonta font family name 

         public synchronized voidsetJavaScriptCanOpenWindowsAutomatically (boolean flag)
Added in API level 1

Tells JavaScript to open windows automatically. This applies to the JavaScript function window.open(). The default is false.

Parameters
flagtrue if JavaScript can open windows automatically 

告诉JavaScript来自动打开的窗口。这适用于JavaScript函数window.open()。默认的是假的。


         public synchronized voidsetJavaScriptEnabled (boolean flag)
Added in API level 1

Tells the WebView to enable JavaScript execution. The default is false.

Parameters
flagtrue if the WebView should execute JavaScript 


         public void setLoadWithOverviewMode(boolean overview)
Added in API level 7

Sets whether the WebView loads pages in overview mode. The default is false. 



         public synchronized voidsetRenderPriority (WebSettings.RenderPriority priority)
Added in API level 1

This method was deprecated in API level 18.
It is not recommended to adjust thread priorities, and this will not be supported in future versions.

Sets the priority of the Render thread. Unlike the other settings, this one only needs to be called once per process. The default value isNORMAL.

Parameters
prioritythe priority

这是不建议调整线程优先级,这将在未来的版本中不支持。
设置渲染线程的优先级。不同于其他设置,只需要调用一次每个进程。默认值是正常的。


         public synchronized voidsetTextSize (WebSettings.TextSize t)
Added in API level 1

This method was deprecated in API level 14.
Use setTextZoom(int) instead.

Sets the text size of the page. The default is NORMAL.

Parameters
tthe text size as a WebSettings.TextSize value

         public synchronized voidsetTextZoom (int textZoom)
Added in API level 14

Sets the text zoom of the page in percent. The default is 100.

Parameters
textZoomthe text zoom in percent 


实例例子:

小demo


private void setWebView() {
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setBuiltInZoomControls(false);
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setRenderPriority(RenderPriority.HIGH);
webSettings.setEnableSmoothTransition(true);
String appCachePath = activity.getDir("netCache", Context.MODE_PRIVATE)
.getAbsolutePath();
webSettings.setAppCacheEnabled(true);
webSettings.setAppCachePath(appCachePath);
webSettings.setAppCacheMaxSize(1024 * 1024 * 5);
/*LOAD_CACHE_ONLY:  不使用网络,只读取本地缓存数据
LOAD_DEFAULT:  根据cache-control决定是否从网络上取数据。
LOAD_CACHE_NORMAL: API level 17中已经废弃, 从API level 11开始作用同LOAD_DEFAULT模式
LOAD_NO_CACHE: 不使用缓存,只从网络获取数据.
LOAD_CACHE_ELSE_NETWORK,只要本地有,无论是否过期,或者no-cache,都使用缓存中的数据。*/
//判断是否有网络,有的话,使用LOAD_DEFAULT或LOAD_NO_CACHE,无网络时,使用LOAD_CACHE_ELSE_NETWORK
if(isConnecting()){
//默认使用网络获取!
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); 
}else{
//如果内容已经存在cache 则使用cache,即使是过去的历史记录。如果cache中不存在,从网络中获取!
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
// webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //默认不使用缓存!
webSettings.setDatabaseEnabled(true);
webSettings.setDomStorageEnabled(true);
String databasePath = activity
.getDir("databases", Context.MODE_PRIVATE).getPath();
webSettings.setDatabasePath(databasePath);


mWebView.setWebViewClient(new MonitorWebClient());
DebugUtil.d("apptest-webUrl", webUrl+"--");
// mWebView.loadUrl(PropertiesUtil.getConfigProperties(Config.AgreementUser));
mWebView.loadUrl(webUrl);
mWebView.setWebChromeClient(new AppCacheWebChromeClient());
}


private class MonitorWebClient extends WebViewClient {


@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// 错误提示
// alertToast("没有网络!");
// 错误处理
try {
mWebView.stopLoading();
} catch (Exception e) {
}
try {
mWebView.clearView();
} catch (Exception e) {
}
if (mWebView.canGoBack()) {
mWebView.goBack();
}
// view.loadUrl("file:///android_asset/error.png");
lyNoNetwork.setVisibility(View.VISIBLE);
mWebView.setVisibility(View.INVISIBLE);
}


@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
// 忽略证书的错误继续Load页面内容
handler.proceed();
}


@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// 显示加载圈显示
progressDialog.show();
super.onPageStarted(view, url, favicon);
}


@Override
public void onPageFinished(WebView view, String url) {
progressDialog.hide();
super.onPageFinished(view, url);
}




}


private class AppCacheWebChromeClient extends WebChromeClient {
@SuppressWarnings("deprecation")
@Override
public void onReachedMaxAppCacheSize(long spaceNeeded,
long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
quotaUpdater.updateQuota(spaceNeeded * 2);
}
}


private void onClickListener() {


iv_Back.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {


// setResult(MainActivity.FLAG_RSP_JUST_RETURN);
finish();
}
});
}






使用webview的另外一种方式:  

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
setContentView(webview);

String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadUrl("http://www.baidu.com");
}

注意    我们可以在activity里面获得this,  webview 我们不需要将其放在xml文件里面也可以直接给与调用。

通过new出来一个webview    随后进行相关的加载就可以。






如果想WebView能够访问网络,必须在AndroidManifest.xml里面添加权限

[html]  view plain copy
  1. <uses-permission android:name="android.permission.INTERNET" />  

main.xml很简单,就是一个WebView

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <WebView  
  8.         android:id="@+id/webView"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="fill_parent" />  
  11.   
  12. </LinearLayout>  

WebViewDemoActivity.java代码:

[java]  view plain copy
  1. package com.tianjf;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.webkit.WebView;  
  6.   
  7. public class WebViewDemoActivity extends Activity {  
  8.   
  9.     private WebView mWebView;  
  10.   
  11.     @Override  
  12.     public void onCreate(Bundle savedInstanceState) {  
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.main);  
  15.   
  16.         mWebView = (WebView) findViewById(R.id.webView);  
  17.   
  18.         // 得到WebSettings对象,设置支持JavaScript参数   
  19.         // 如果访问的页面中有JavaScript,则WebView必须设置支持JavaScript ,否则显示空白页面   
  20.         mWebView.getSettings().setJavaScriptEnabled(true);  
  21.         // 加载URL   
  22.         mWebView.loadUrl("http://www.baidu.com/");  
  23.     }  
  24. }  

运行一下就会看到URL被正确load出来了。

但是有个问题,当点击链接继续浏览,则会弹出系统默认的Browser,为了能够继续在WebView中浏览,要用到shouldOverrideUrlLoading方法:

[java]  view plain copy
  1. @Override  
  2. public void onCreate(Bundle savedInstanceState) {  
  3.   
  4.     。。。。。。。。。。。。。。。。。。。。。。。。                  
  5.   
  6.     // 虽然Google主页在WebView中显示了,但是如果点击链接继续浏览,则会显示到系统默认的Browser中   
  7.     // 为了继续在WebView中显示,需要重写shouldOverrideUrlLoading方法   
  8.     mWebView.setWebViewClient(new MyWebViewClient());  
  9.          
  10.   
  11.     。。。。。。。。。。。。。。。。。。。。。。。。          
  12.        }  
  13.   
  14. private class MyWebViewClient extends WebViewClient {  
  15.     @Override  
  16.     public boolean shouldOverrideUrlLoading(WebView view, String url) {  
  17.         view.loadUrl(url);  
  18.         return true;  
  19.     }  
  20. }  


另外,如果想按回退键回到上一个页面,那么

[java]  view plain copy
  1. /** 
  2.  * 按back键可以回到上个网页 
  3.  */  
  4. @Override  
  5. public boolean onKeyDown(int keyCode, KeyEvent event) {  
  6.     if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {  
  7.         mWebView.goBack();  
  8.         return true;  
  9.     }  
  10.     return super.onKeyDown(keyCode, event);  
  11. }  

对于Android 2.0开始又多出了一种新的方法,对于Activity 可以单独获取Back键的按下事件,直接重写onBackPressed 方法即可,代码如下

[java]  view plain copy
  1. @Override  
  2. public void onBackPressed() {  
  3.  // 这里处理逻辑代码,该方法仅适用于2.0或更高版本的sdk   
  4. return ;  
  5. }  

如果想加载工程中的HTML,那么可以用到下面的方法(前提是HTML放在assets目录中)

[java]  view plain copy
  1. mWebView.loadUrl("file:///android_asset/test.html");  

如果想直接load一段HTML文,可以用下面的方法

[java]  view plain copy
  1. mWebView.loadData("<html><body>abcdefg</body></html>""text/html""utf-8");  

下面是WebView其他的一下用法:

设置允许访问文件数据

[java]  view plain copy
  1. mWebView.getSettings().setAllowFileAccess(true);  

设置支持缩放

[java]  view plain copy
  1. mWebView.getSettings().setBuiltInZoomControls(true);  

设置是否保存密码

[java]  view plain copy
  1. mWebView.getSettings().setSavePassword(false);  

设置支持各种不同的设备

[java]  view plain copy
  1. mWebView.getSettings().setUserAgentString("Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X;en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334bSafari/531.21.10");  

加载webview网页时所要执行的一些方法

[java]  view plain copy
  1. mWebView.setWebViewClient(new WebViewClient() {  
  2.         // 新开页面时用自己定义的webview来显示,不用系统自带的浏览器来显示   
  3.         @Override  
  4.         public boolean shouldOverrideUrlLoading(WebView view, String url) {  
  5.             view.loadUrl(url);  
  6.             return true;  
  7.         }  
  8.           
  9.         // 开始加载网页时要做的工作   
  10.         @Override  
  11.         public void onPageStarted(WebView view, String url, Bitmap favicon) {  
  12.             super.onPageStarted(view, url, favicon);  
  13.         }  
  14.           
  15.         // 加载完成时要做的工作   
  16.         @Override  
  17.         public void onPageFinished(WebView view, String url) {  
  18.             super.onPageFinished(view, url);  
  19.         }  
  20.           
  21.         // 加载错误时要做的工作   
  22.         @Override  
  23.         public void onReceivedError(WebView view, int errorCode,  
  24.                 String description, String failingUrl) {  
  25.             super.onReceivedError(view, errorCode, description, failingUrl);  
  26.         }  
  27.     });  

处理网页中的一些对话框信息(提示对话框,带选择的对话框,带输入的对话框)

[java]  view plain copy
  1. mWebView.setWebChromeClient(new WebChromeClient() {  
  2.         // 提示对话框   
  3.         @Override  
  4.         public boolean onJsAlert(WebView view, String url, String message,  
  5.                 final JsResult result) {  
  6.             // 构建一个Builder来显示网页中的alert对话框   
  7.             Builder builder = new Builder(WebViewDemoActivity.this);  
  8.             builder.setTitle("提示对话框");  
  9.             builder.setMessage(message);  
  10.             builder.setPositiveButton(android.R.string.ok,  
  11.                     new AlertDialog.OnClickListener() {  
  12.                         @Override  
  13.                         public void onClick(DialogInterface dialog,  
  14.                                 int which) {  
  15.                             result.confirm();  
  16.                         }  
  17.                     });  
  18.             builder.setCancelable(false);  
  19.             builder.create();  
  20.             builder.show();  
  21.             return true;  
  22.         }  
  23.   
  24.         // 带按钮的对话框   
  25.         @Override  
  26.         public boolean onJsConfirm(WebView view, String url,  
  27.                 String message, final JsResult result) {  
  28.             Builder builder = new Builder(WebViewDemoActivity.this);  
  29.             builder.setTitle("带选择的对话框");  
  30.             builder.setMessage(message);  
  31.             builder.setPositiveButton(android.R.string.ok,  
  32.                     new AlertDialog.OnClickListener() {  
  33.                         @Override  
  34.                         public void onClick(DialogInterface dialog,  
  35.                                 int which) {  
  36.                             result.confirm();  
  37.                         }  
  38.                     });  
  39.             builder.setNeutralButton(android.R.string.cancel,  
  40.                     new AlertDialog.OnClickListener() {  
  41.                         @Override  
  42.                         public void onClick(DialogInterface dialog,  
  43.                                 int which) {  
  44.                             result.cancel();  
  45.                         }  
  46.                     });  
  47.             builder.setCancelable(false);  
  48.             builder.create();  
  49.             builder.show();  
  50.             return true;  
  51.         }  
  52.   
  53.         // 带输入框的对话框   
  54.         @Override  
  55.         public boolean onJsPrompt(WebView view, String url, String message,  
  56.                 String defaultValue, final JsPromptResult result) {  
  57.             LayoutInflater inflater = LayoutInflater  
  58.                     .from(WebViewDemoActivity.this);  
  59.             final View v = inflater.inflate(R.layout.myDialog, null);  
  60.             // 设置 TextView对应网页中的提示信息   
  61.             ((TextView) v.findViewById(R.id.textView)).setText(message);  
  62.             // 设置EditText对应网页中的输入框   
  63.             ((EditText) v.findViewById(R.id.editText))  
  64.                     .setText(defaultValue);  
  65.   
  66.             Builder builder = new Builder(WebViewDemoActivity.this);  
  67.             builder.setTitle("带输入的对话框");  
  68.             builder.setView(v);  
  69.             builder.setPositiveButton(android.R.string.ok,  
  70.                     new AlertDialog.OnClickListener() {  
  71.                         @Override  
  72.                         public void onClick(DialogInterface dialog,  
  73.                                 int which) {  
  74.                             String value = ((EditText) v  
  75.                                     .findViewById(R.id.editText)).getText()  
  76.                                     .toString();  
  77.                             result.confirm(value);  
  78.                         }  
  79.                     });  
  80.             builder.setNegativeButton(android.R.string.cancel,  
  81.                     new AlertDialog.OnClickListener() {  
  82.                         @Override  
  83.                         public void onClick(DialogInterface dialog,  
  84.                                 int which) {  
  85.                             result.cancel();  
  86.                         }  
  87.                     });  
  88.             builder.setOnCancelListener(new DialogInterface.OnCancelListener() {  
  89.                 @Override  
  90.                 public void onCancel(DialogInterface dialog) {  
  91.                     result.cancel();  
  92.                 }  
  93.             });  
  94.             builder.create();  
  95.             builder.show();  
  96.             return true;  
  97.         }  
  98.   
  99.         // 设置网页加载的进度条   
  100.         @Override  
  101.         public void onProgressChanged(WebView view, int newProgress) {  
  102.             WebViewDemoActivity.this.getWindow().setFeatureInt(  
  103.                     Window.FEATURE_PROGRESS, newProgress * 100);  
  104.             super.onProgressChanged(view, newProgress);  
  105.         }  
  106.           
  107.         // 设置应用程序的标题   
  108.         @Override  
  109.         public void onReceivedTitle(WebView view, String title) {  
  110.             WebViewDemoActivity.this.setTitle(title);  
  111.             super.onReceivedTitle(view, title);  
  112.         }  
  113.     });                                                                                           
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值