WebSettings 文档 API 翻译 常用设置


WebSettings 介绍

public abstract class android.webkit.WebSettings extends Object 
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. A WebSettings object obtained from WebView.getSettings() is tied to the life of the WebView. If a WebView has been destroyed, any method call on WebSettings will throw an IllegalStateException.
管理WebView的设置状态。 首次创建WebView时,会获取一组默认设置。 这些默认设置将从任何getter调用返回。 从WebView.getSettings()获取的WebSettings对象与WebView的使用寿命相关。 如果WebView已被销毁,调用WebSettings上的任何方法都将抛出一个IllegalStateException异常。

This is an abstract base class: concrete WebViewProviders must create a class derived from this, and return an instance of it in the WebViewProvider.getWebSettingsProvider() method implementation.
这是一个抽象的基类:具体的WebViewProvider必须创建一个从此派生的类,并在WebViewProvider.getWebSettingsProvider()方法实现中返回一个实例。

WebSettings API

一个静态方法
static  String  getDefaultUserAgent(Context context)  Returns the default User-Agent used by a WebView.

其他的全部是set和get方法,其中 蓝色代表既有get方法也有set方法,黑色代表没有相应的get方法,灰色代表废弃的方法。
  1. setAllowContentAccess(boolean allow)  Enables or disables content URL access within WebView. The default is enabled
  2. setAllowFileAccess(boolean allow)  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.
  3. setAllowFileAccessFromFileURLs(boolean flag)  Sets whether JavaScript running in the context of a file scheme URL should be allowed to access content from other file scheme URLs. The default value is true for API level ICE_CREAM_SANDWICH_MR1 and below, and false for API level JELLY_BEAN and above.
  4. setAllowUniversalAccessFromFileURLs(boolean flag)  Sets whether JavaScript running in the context of a file scheme URL should be allowed to access content from any origin. The default value is true for API level ICE_CREAM_SANDWICH_MR1 and below, and false for API level JELLY_BEAN and above.
  5. setAppCacheEnabled(boolean flag)  Sets whether the Application Caches API should be enabled. The default is false.
  6. setAppCacheMaxSize(long appCacheMaxSize)  This method was deprecated in API level 18. In future quota will be managed automatically. The default size is MAX_VALUE. 
  7. setAppCachePath(String appCachePath)  Sets the path to the Application Caches files. This method should only be called once: repeated calls are ignored. 
  8. setBlockNetworkImage(boolean flag)  Sets whether the WebView should not load image resources from the network (resources accessed via http and https URI schemes).The default is false.
  9. setBlockNetworkLoads(boolean flag)  Sets whether the WebView should not load resources from the network. The default value is false if the application has the INTERNET permission, otherwise it is true.
  10. setBuiltInZoomControls(boolean enabled)  Sets whether the WebView should use its built-in zoom mechanisms. The default is false.
  11. setCacheMode(int mode)  Overrides the way the cache is used. The default value is LOAD_DEFAULT.
  12. setCursiveFontFamily(String font)  Sets the cursive font family name. The default is "cursive".
  13. setDatabaseEnabled(boolean flag)  Sets whether the database storage API is enabled. The default value is false
  14. setDatabasePath(String databasePath)  This method was deprecated in API level 19. Database paths are managed by the implementation and calling this method will have no effect.  This method should only be called once: repeated calls are ignored.
  15. setDefaultFixedFontSize(int size)  Sets the default fixed font size. The default is 16.
  16. setDefaultFontSize(int size)  Sets the default font size. The default is 16. 
  17. setDefaultTextEncodingName(String encoding)  Sets the default text encoding name to use when decoding html pages. The default is "UTF-8".
  18. setDefaultZoom(WebSettings.ZoomDensity zoom)  This method was deprecated in API level 19. This method is no longer supported, see the function documentation for recommended alternatives.  The default is MEDIUM.
  19. setDisabledActionModeMenuItems(int menuItems)  Disables the action mode menu items according to menuItems flag.
  20. setDisplayZoomControls(boolean enabled)  Sets whether the WebView should display on-screen zoom controls when using the built-in zoom mechanisms. The default is true.
  21. setDomStorageEnabled(boolean flag)  Sets whether the DOM storage API is enabled. The default value is false.
  22. setEnableSmoothTransition(boolean enable)  This method was deprecated in API level 17. This method is now obsolete, and will become a no-op in future.  The default value is false.
  23. setFantasyFontFamily(String font)  Sets the fantasy font family name. The default is "fantasy".
  24. setFixedFontFamily(String font)  Sets the fixed font family name. The default is "monospace".
  25. setGeolocationDatabasePath(String databasePath)  This method was deprecated in API level 24. Geolocation database are managed by the implementation and calling this method will have no effect.
  26. setGeolocationEnabled(boolean flag)  Sets whether Geolocation is enabled. The default is true.
  27. setJavaScriptCanOpenWindowsAutomatically(boolean flag)  Tells JavaScript to open windows automatically. The default is false.
  28. setJavaScriptEnabled(boolean flag)  Tells the WebView to enable JavaScript execution. The default is false.
  29. setLayoutAlgorithm(WebSettings.LayoutAlgorithm l)  Sets the underlying layout algorithm. The default is NARROW_COLUMNS.
  30. setLightTouchEnabled(boolean enabled)  This method was deprecated in API level 18. From JELLY_BEAN this setting is obsolete and has no effect.
  31. setLoadWithOverviewMode(boolean overview)  Sets whether the WebView loads pages in overview mode, that is, zooms out the content to fit on screen by width.  The default is false.
  32. setLoadsImagesAutomatically(boolean flag)  Sets whether the WebView should load image resources. The default is true.
  33. setMediaPlaybackRequiresUserGesture(boolean require)  Sets whether the WebView requires a user gesture to play media. The default is true.
  34. setMinimumFontSize(int size)  Sets the minimum font size. The default is 8.
  35. setMinimumLogicalFontSize(int size)  Sets the minimum logical font size. The default is 8.
  36. setMixedContentMode(int mode)  Configures the WebView's behavior when a secure origin attempts to load a resource from an insecure origin. By default, apps that target KITKAT or below default to MIXED_CONTENT_ALWAYS_ALLOW. Apps targeting LOLLIPOP default to MIXED_CONTENT_NEVER_ALLOW.
  37. setNeedInitialFocus(boolean flag)  Tells the WebView whether it needs to set a node to have focus when requestFocus(int, android.graphics.Rect) is called. The default value is true.
  38. setOffscreenPreRaster(boolean enabled)  Sets whether this WebView should raster tiles when it is offscreen but attached to a window. The default value is false.
  39. setPluginState(WebSettings.PluginState state)  This method was deprecated in API level 18. Plugins will not be supported in future, and should not be used.  The default is OFF.
  40. setRenderPriority(WebSettings.RenderPriority priority)  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.  The default value is NORMAL.
  41. setSafeBrowsingEnabled(boolean enabled)  Sets whether Safe Browsing is enabled. Safe browsing is disabled by default. 
  42. setSansSerifFontFamily(String font)  Sets the sans-serif font family name. The default is "sans-serif".
  43. setSaveFormData(boolean save)  Sets whether the WebView should save form data.  In Android O, the platform has implemented a fully functional Autofill feature to store form data. Therefore, the Webview form data save feature is disabled. Note that the feature will continue to be supported on older versions of Android as before. This function does not have any effect.
  44. setSavePassword(boolean save)  This method was deprecated in API level 18. Saving passwords in WebView will not be supported in future versions.  The default is true.
  45. setSerifFontFamily(String font)  Sets the serif font family name. The default is "sans-serif".
  46. setStandardFontFamily(String font)  Sets the standard font family name. The default is "sans-serif".
  47. setSupportMultipleWindows(boolean support)  Sets whether the WebView whether supports multiple windows. The default is false.
  48. setSupportZoom(boolean support)  Sets whether the WebView should support zooming using its on-screen zoom controls and gestures. The default is true.
  49. setTextSize(WebSettings.TextSize t)  This method was deprecated in API level 14. Use setTextZoom(int) instead.  The default is NORMAL.
  50. setTextZoom(int textZoom)  Sets the text zoom of the page in percent. The default is 100.
  51. setUseWideViewPort(boolean use)  Sets whether the WebView should enable support for the "viewport" HTML meta tag or should use a wide viewport.
  52. setUserAgentString(String ua)  Sets the WebView's user-agent string. Note that starting from KITKAT Android version, changing the user-agent while loading a web page causes WebView to initiate loading once again.

WebSettings API 翻译

  1. setAllowContentAccess (boolean allow):是否允许在WebView中访问内容URL(Content Url),默认允许。内容Url访问允许WebView从安装在系统中的内容提供者载入内容。
  2. setAllowFileAccess (boolean allow):是否允许访问文件,默认允许。注意,这里只是允许或禁止对文件系统的访问,Assets 和 resources 文件使用file:///android_asset和file:///android_res仍是可访问的。
  3. setAllowFileAccessFromFileURLs (boolean flag):是否允许运行在一个URL环境(the context of a file scheme URL)中的JavaScript访问来自其他URL环境的内容,为了保证安全,应该不允许。也请注意,这项设置只影响对file schema 资源的javascript访问,其他形式的访问,例如来自图片HTML单元的访问不受影响。为了防止相同的域策略(same domain policy)对ICE_CREAM_SANDWICH以及更老机型的侵害,应该显式地设置此值为false。
  4. setAllowUniversalAccessFromFileURLs (boolean flag):是否允许运行在一个file schema URL环境下的JavaScript访问来自其他任何来源的内容,包括其他file schema URLs. 参见setAllowFileAccessFromFileURLs(boolean),为了确保安全,应该设置为不允许,注意这项设置只影响对file schema 资源的JavaScript访问,其他形式的访问,例如来自图片HTML单元的访问不受影响。为了防止相同的域策略(same domain policy)对ICE_CREAM_SANDWICH以及更老机型的侵害,应该显式地设置此值为false。ICE_CREAM_SANDWICH_MR1 以及更老的版本此默认值为true,JELLY_BEAN以及更新版本此默认值为false
  5. setAppCacheEnabled (boolean flag):应用缓存API是否可用,默认值false, 结合setAppCachePath(String)使用。
  6. setAppCachePath(String):设置应用缓存文件的路径。为了让应用缓存API可用,此方法必须传入一个应用可写的路径。该方法只会执行一次,重复调用会被忽略。
  7. setAppCacheMaxSize (long appCacheMaxSize):已废弃。设置应用缓存内容的最大值。所传值会被近似为数据库支持的最近似值,因此这是一个指示值,而不是一个固定值。所传值若小于数据库大小不会让数据库调整大小。默认值是MAX_VALUE,建议将默认值设置为最大值。
  8. setBlockNetworkImage (boolean flag):是否禁止从网络(通过http和https URI schemes访问的资源)下载图片资源,默认值为false。注意,除非getLoadsImagesAutomatically()返回true,否则该方法无效。还请注意,即使此项设置为false,使用setBlockNetworkLoads(boolean)禁止所有网络加载也会阻止网络图片的加载。当此项设置的值从true变为false,WebView当前显示的内容所引用的网络图片资源会自动获取。
  9. setBlockNetworkLoads (boolean flag):是否禁止从网络下载数据,如果app有INTERNET权限,默认值为false,否则默认为true。使用setBlockNetworkImage(boolean) 只会禁止图片资源的加载。注意此值由true变为false,当前WebView展示的内容所引用的网络资源不会自动加载,直到调用了重载。如果APP没有INTERNET权限,设置此值为false会抛出SecurityException。
  10. setBuiltInZoomControls (boolean enabled):是否使用内置的缩放机制。内置的缩放机制包括屏幕上的缩放控件(浮于WebView内容之上)和缩放手势的运用。通过setDisplayZoomControls(boolean)可以控制是否显示这些控件,默认值为false。
  11. setCacheMode (int mode):重写使用缓存的方式,默认值LOAD_DEFAULT。缓存的使用方式基于导航类型,正常的页面加载,检测缓存,需要时缓存内容复现。导航返回时,内容不会复现,只有内容会从缓存盘中恢复。该方法允许客户端通过指定LOAD_DEFAULT, LOAD_CACHE_ELSE_NETWORK, LOAD_NO_CACHE or LOAD_CACHE_ONLY的其中一项来重写其行为。
  12. setCursiveFontFamily (String font):设置WebView字体库字体,默认“cursive”
  13. setDatabaseEnabled (boolean flag):数据库存储API是否可用,默认值false。如何正确设置数据存储API参见setDatabasePath(String)。该设置对同一进程中的所有WebView实例均有效。注意,只能在当前进程的任意WebView加载页面之前修改此项,因为此节点之后WebView的实现类可能会忽略该项设置的改变。
  14. setDatabasePath (String databasePath):已废弃,数据库路径由实现(implementation)管理,调用此方法无效。 设置数据库的存储路径,为了保证数据库正确运行,该方法必须使用一个应用可写的路径。此方法只能执行一次,重复调用会被忽略。
  15. setDefaultFixedFontSize (int size):设置默认固定的字体大小,默认为16,可取值1到72
  16. setDefaultFontSize (int size):设置默认的字体大小,默认16,可取值1到72
  17. setDefaultTextEncodingName (String encoding):设置默认的字符编码集,默认”UTF-8”.
  18. setDefaultZoom (WebSettings.ZoomDensity zoom):已废弃。设置默认的缩放密度,必须在UI线程调用,默认值MEDIUM.该项设置在新应用中不推荐使用。如果WebView用于展示手机页面,可以通过调整页面的’meta viewport’ 标记中的’width’ 和 ‘initial-scale’属性实现预期效果,对于漏用标记的页面,可以使用setInitialScale(int)和setUseWideViewPort(boolean) .
  19. setDisabledActionModeMenuItems(int menuItems)  根据menuItems标志禁用"动作模式菜单项 ActionModeMenuItems"。
  20. setDisplayZoomControls (boolean enabled):使用内置的缩放机制时是否展示缩放控件,默认值true。参见setBuiltInZoomControls(boolean).
  21. setDomStorageEnabled (boolean flag):DOM存储API是否可用,默认false。
  22. setEnableSmoothTransition (boolean enable):已废弃,将来会成为空操作(no-op),设置当panning或者缩放或者持有当前WebView的window没有焦点时是否允许其光滑过渡,若为true,WebView会选择一个性能最大化的解决方案。例如过渡时WebView的内容可能不更新。若为false,WebView会保持精度(fidelity),默认值false。
  23. setFantasyFontFamily (String font):设置fantasy字体集(font family)的名字默认为“fantasy”
  24. setFixedFontFamily (String font):设置固定的字体集的名字,默认为”monospace”。
  25. setGeolocationDatabasePath (String databasePath):定位数据库的保存路径,为了确保定位权限和缓存位置的持久化,该方法应该传入一个应用可写的路径。
  26. setGeolocationEnabled (boolean flag):定位是否可用,默认为true。请注意,为了确保定位API在WebView的页面中可用,必须遵守如下约定: 
  • app必须有定位的权限,参见ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION; 
  • app必须提供onGeolocationPermissionsShowPrompt(String, GeolocationPermissions.Callback)回调方法的实现,在页面通过JavaScript定位API请求定位时接收通知。 
  • 作为可选项,可以在数据库中存储历史位置和Web初始权限,参见setGeolocationDatabasePath(String).
setJavaScriptCanOpenWindowsAutomatically (boolean flag):让JavaScript自动打开窗口,默认false。适用于JavaScript方法window.open()。 setJavaScriptEnabled (boolean flag):设置WebView是否允许执行JavaScript脚本,默认false,不允许。 setLayoutAlgorithm (WebSettings.LayoutAlgorithm l):设置布局,会引起WebView的重新布局(relayout),默认值NARROW_COLUMNS setLightTouchEnabled (boolean enabled):已废弃。从 JELLY_BEAN 开始,该设置无效。允许使用轻触摸做出选择和光标悬停。 setLoadWithOverviewMode (boolean overview):设置WebView是否在概览模式下加载页面,也就是缩放内容以适应屏幕宽度。 默认值为false。 该项设置在内容宽度超出WebView控件的宽度时生效,例如当getUseWideViewPort() 返回true时。 setLoadsImagesAutomatically (boolean flag):WebView是否下载图片资源,默认为true。注意,该方法控制所有图片的下载,包括使用URI嵌入的图片(使用setBlockNetworkImage(boolean) 只控制使用网络URI的图片的下载)。如果该设置项的值由false变为true,WebView展示的内容所引用的所有的图片资源将自动下载。 setMediaPlaybackRequiresUserGesture (boolean require):WebView是否需要用户的手势进行媒体播放,默认值为true。 setMinimumFontSize (int size):设置最小的字号,默认为8 setMinimumLogicalFontSize (int size):设置最小的本地字号,默认为8。 setMixedContentMode (int mode):当一个安全的来源(origin)试图从一个不安全的来源加载资源时配置WebView的行为。默认情况下,KITKAT及更低版本默认值为MIXED_CONTENT_ALWAYS_ALLOW,LOLLIPOP版本默认值MIXED_CONTENT_NEVER_ALLOW,WebView首选的最安全的操作模式为MIXED_CONTENT_NEVER_ALLOW ,不鼓励使用MIXED_CONTENT_ALWAYS_ALLOW。 setNeedInitialFocus (boolean flag):调用requestFocus(int, Android.graphics.Rect)时是否需要设置节点获取焦点,默认值为true。 setOffscreenPreRaster (boolean enabled):当WebView切换到后台但仍然与窗口关联时是否raster tiles,打开它可以避免在WebView从后台切换到前台时重新绘制,默认值false。在这种模式下后台的WebView占用更多的内存。请按如下准则显示内存的使用:
  • WebView的尺寸不能比设备的屏幕尺寸更大;
  • 限制在少数WebView上使用该模式;
  • 在可见的WebView和即将显现的WebView上使用;
setPluginState (WebSettings.PluginState state):在API18以上已废弃。未来将不支持插件,不要使用。告诉WebView启用、禁用或者有即用(on demand)的插件,即用模式是指如果存在一个可以处理嵌入内容的插件,会显示一个占位图标,点击时开启。默认值OFF。 setRenderPriority (WebSettings.RenderPriority priority):在API18以上已废弃。不建议调整线程优先级,未来版本不会支持这样做。设置绘制(Render,很多书上翻译成渲染,貌似很专业,但是不易懂,不敢苟同)线程的优先级。不像其他设置,同一进程中只需调用一次,默认值NORMAL。setSafeBrowsingEnabled(boolean enabled):设置是否启用安全浏览。 默认情况下禁用安全浏览。
setSansSerifFontFamily (String font):设置无衬线字体集(sans-serif font family)的名字。默认值”sans-serif”. setSaveFormData (boolean save):WebView是否保存表单数据,默认值true。 setSavePassword (boolean save):API18以上版本已废弃。未来版本将不支持保存WebView中的密码。设置WebView是否保存密码,默认true。 setSerifFontFamily (String font):设置衬线字体集(serif font family)的名字,默认“sans-serif”。 setStandardFontFamily (String font):设置标准字体集的名字,默认值“sans-serif”。 setSupportMultipleWindows (boolean support):设置WebView是否支持多窗口。如果设置为true,主程序要实现onCreateWindow(WebView, boolean, boolean, Message),默认false。 setSupportZoom (boolean support):WebView是否支持使用屏幕上的缩放控件和手势进行缩放,默认值true。设置setBuiltInZoomControls(boolean)可以使用特殊的缩放机制。该项设置不会影响zoomIn() and zoomOut()的缩放操作。 setTextSize (WebSettings.TextSize t):API14版本以上已废弃。请取代使用setTextZoom(int)。设置页面文本的尺寸,默认NORMAL。 setTextZoom (int textZoom):设置页面上的文本缩放百分比,默认100。 setUseWideViewPort (boolean use):WebView是否支持HTML的“viewport”标签或者使用wide viewport。设置值为true时,布局的宽度总是与WebView控件上的设备无关像素(device-dependent pixels)宽度一致。当值为true且页面包含viewport标记,将使用标签指定的宽度。如果页面不包含标签或者标签没有提供宽度,那就使用wide viewport。 setUserAgentString (String ua):设置WebView的用户代理字符串。如果字符串为null或者empty,将使用系统默认值。注意从KITKAT版本开始,加载网页时改变用户代理会让WebView再次初始化加载。

设置模型 WebViewModel

public class WebSettingsModel implements Parcelable {
	//这些搜索引擎都有大量大量的参数可以配置
	public static final String SEARCH_TYPE_BAIDU = "https://www.baidu.com/s?ie=UTF-8&wd=";
	public static final String SEARCH_TYPE_GOOGLE = "https://www.google.com.hk/#safe=strict&q=";
	public static final String SEARCH_TYPE_GITHUB = "https://github.com/search?utf8=%E2%9C%93&q=";
	
	//这些事WebSettings中为setMixedContentMode方法提供的常量,因为只能在5.0以上使用,所以我把他们拷到了这里
	public static final int MIXED_CONTENT_ALWAYS_ALLOW = 0;
	public static final int MIXED_CONTENT_NEVER_ALLOW = 1;
	public static final int MIXED_CONTENT_COMPATIBILITY_MODE = 2;
	
	public String title;
	public String url;
	public String searchType;//Baidu,GitHub,Google等
	public boolean showHorizontalPB;
	public boolean showCenterPB;
	//***************************************************************************************************************
	//                                                                   以下为WebSettings中的同名方法
	//***************************************************************************************************************
	public boolean setBuiltInZoomControls;
	public boolean setDisplayZoomControls;
	public boolean setJavaScriptEnabled;
	public boolean setJavaScriptCanOpenWindowsAutomatically;
	public boolean setUseWideViewPort;
	public boolean setLoadWithOverviewMode;
	public boolean setAppCacheEnabled;
	public boolean setDatabaseEnabled;
	public boolean setDomStorageEnabled;
	public boolean setSupportMultipleWindows;
	public boolean setSupportZoom;
	public boolean setGeolocationEnabled;
	public int setCacheMode;
	public int setMinimumFontSize;
	public int setMixedContentMode;
	public int setTextZoom;
	public WebSettings.LayoutAlgorithm setLayoutAlgorithm;
	
	private WebSettingsModel(Builder builder) {
		searchType = builder.searchType;
		title = builder.title;
		url = builder.url;
		showHorizontalPB = builder.showHorizontalPB;
		showCenterPB = builder.showCenterPB;
		setBuiltInZoomControls = builder.setBuiltInZoomControls;
		setDisplayZoomControls = builder.setDisplayZoomControls;
		setJavaScriptEnabled = builder.setJavaScriptEnabled;
		setJavaScriptCanOpenWindowsAutomatically = builder.setJavaScriptCanOpenWindowsAutomatically;
		setUseWideViewPort = builder.setUseWideViewPort;
		setLoadWithOverviewMode = builder.setLoadWithOverviewMode;
		setAppCacheEnabled = builder.setAppCacheEnabled;
		setDatabaseEnabled = builder.setDatabaseEnabled;
		setDomStorageEnabled = builder.setDomStorageEnabled;
		setSupportMultipleWindows = builder.setSupportMultipleWindows;
		setSupportZoom = builder.setSupportZoom;
		setGeolocationEnabled = builder.setGeolocationEnabled;
		setCacheMode = builder.setCacheMode;
		setMinimumFontSize = builder.setMinimumFontSize;
		setMixedContentMode = builder.setMixedContentMode;
		setTextZoom = builder.setTextZoom;
		setLayoutAlgorithm = builder.setLayoutAlgorithm;
	}
	
	public static Builder newBuilder() {
		return new Builder();
	}
	
	@Override
	public String toString() {
		return "WebSettingsModel{" +
				"searchType='" + searchType + '\'' +
				", title='" + title + '\'' +
				", url='" + url + '\'' +
				", showHorizontalPB=" + showHorizontalPB +
				", showCenterPB=" + showCenterPB +
				", setBuiltInZoomControls=" + setBuiltInZoomControls +
				", setDisplayZoomControls=" + setDisplayZoomControls +
				", setJavaScriptEnabled=" + setJavaScriptEnabled +
				", setJavaScriptCanOpenWindowsAutomatically=" + setJavaScriptCanOpenWindowsAutomatically +
				", setUseWideViewPort=" + setUseWideViewPort +
				", setLoadWithOverviewMode=" + setLoadWithOverviewMode +
				", setAppCacheEnabled=" + setAppCacheEnabled +
				", setDatabaseEnabled=" + setDatabaseEnabled +
				", setDomStorageEnabled=" + setDomStorageEnabled +
				", setSupportMultipleWindows=" + setSupportMultipleWindows +
				", setSupportZoom=" + setSupportZoom +
				", setGeolocationEnabled=" + setGeolocationEnabled +
				", setCacheMode=" + setCacheMode +
				", setMinimumFontSize=" + setMinimumFontSize +
				", setMixedContentMode=" + setMixedContentMode +
				", setTextZoom=" + setTextZoom +
				", setLayoutAlgorithm=" + setLayoutAlgorithm +
				'}';
	}
	
	public static final class Builder {
		//***************************************************************************************************************
		//                                                                             在这里设置默认值
		//***************************************************************************************************************
		private String title = "默认的TITLE";
		private String url = "https://github.com/baiqiantao";
		private boolean showHorizontalPB = false;
		private boolean showCenterPB = false;
		private String searchType = "baidu";
		//以下默认值均是WebSettings中同名get方法获取到的默认值
		private boolean setAppCacheEnabled = false;//应用缓存API可用(启动应用缓存)
		private boolean setBuiltInZoomControls = false;//使用内置的缩放机制,包括屏幕上的缩放控件和双指缩放手势
		private int setCacheMode = WebSettings.LOAD_DEFAULT;//使用缓存的方式,默认值LOAD_DEFAULT,LOAD_NO_CACHE
		private boolean setDatabaseEnabled = false;//数据库存储API可用
		private boolean setDisplayZoomControls = true;//是否显示缩放控件。setDisplayZoomControls设为true时才有效
		private boolean setDomStorageEnabled = false;//DOM存储API可用
		private boolean setGeolocationEnabled = true;//定位可用。需要有定位权限和实现onGeolocationPermissionsShowPrompt回调方法
		private boolean setJavaScriptCanOpenWindowsAutomatically = false;//让js自动打开窗口,适用于js方法window.open()
		private boolean setJavaScriptEnabled = false;//允许js交互
		private boolean setLoadWithOverviewMode = false;//是否在概览模式下加载页面,也就是缩放内容以适应屏幕宽度
		private int setMinimumFontSize = 8;//设置最小的字号,默认为8
		private int setMixedContentMode = WebSettingsModel.MIXED_CONTENT_NEVER_ALLOW;//设置混合模式
		//5.0开始默认的混合模式为MIXED_CONTENT_NEVER_ALLOW,即不允许使用混合模式,即https中不能加载http资源
		private boolean setSupportMultipleWindows = false;//支持多窗口。如果设置为true,需要实现onCreateWindow回调方法
		private boolean setSupportZoom = true;//是否支持使用屏幕上的缩放控件和手势进行缩放
		private int setTextZoom = 100;//设置页面上的文本缩放百分比,默认100
		private boolean setUseWideViewPort = false;//重要!布局的宽度总是与WebView控件上的设备无关像素宽度一致
		private WebSettings.LayoutAlgorithm setLayoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS;//设置布局
		//会引起WebView重新布局。默认值NARROW_COLUMNS(适应内容大小),SINGLE_COLUMN(适应屏幕,内容将自动缩放)
		
		private Builder() {
		}
		
		public Builder title(String val) {
			title = val;
			return this;
		}
		
		public Builder url(String val) {
			url = val;
			return this;
		}
		
		public Builder showHorizontalPB(boolean val) {
			showHorizontalPB = val;
			return this;
		}
		
		public Builder showCenterPB(boolean val) {
			showCenterPB = val;
			return this;
		}
		
		public Builder searchType(String val) {
			searchType = val;
			return this;
		}
		
		public Builder setBuiltInZoomControls(boolean val) {
			setBuiltInZoomControls = val;
			return this;
		}
		
		public Builder setDisplayZoomControls(boolean val) {
			setDisplayZoomControls = val;
			return this;
		}
		
		public Builder setJavaScriptEnabled(boolean val) {
			setJavaScriptEnabled = val;
			return this;
		}
		
		public Builder setJavaScriptCanOpenWindowsAutomatically(boolean val) {
			setJavaScriptCanOpenWindowsAutomatically = val;
			return this;
		}
		
		public Builder setUseWideViewPort(boolean val) {
			setUseWideViewPort = val;
			return this;
		}
		
		public Builder setLoadWithOverviewMode(boolean val) {
			setLoadWithOverviewMode = val;
			return this;
		}
		
		public Builder setAppCacheEnabled(boolean val) {
			setAppCacheEnabled = val;
			return this;
		}
		
		public Builder setDatabaseEnabled(boolean val) {
			setDatabaseEnabled = val;
			return this;
		}
		
		public Builder setDomStorageEnabled(boolean val) {
			setDomStorageEnabled = val;
			return this;
		}
		
		public Builder setSupportMultipleWindows(boolean val) {
			setSupportMultipleWindows = val;
			return this;
		}
		
		public Builder setSupportZoom(boolean val) {
			setSupportZoom = val;
			return this;
		}
		
		public Builder setGeolocationEnabled(boolean val) {
			setGeolocationEnabled = val;
			return this;
		}
		
		public Builder setCacheMode(int val) {
			setCacheMode = val;
			return this;
		}
		
		public Builder setMinimumFontSize(int val) {
			setMinimumFontSize = val;
			return this;
		}
		
		public Builder setMixedContentMode(int val) {
			setMixedContentMode = val;
			return this;
		}
		
		public Builder setTextZoom(int val) {
			setTextZoom = val;
			return this;
		}
		
		public Builder setLayoutAlgorithm(WebSettings.LayoutAlgorithm val) {
			setLayoutAlgorithm = val;
			return this;
		}
		
		public WebSettingsModel build() {
			return new WebSettingsModel(this);
		}
	}
	
	@Override
	public int describeContents() {
		return 0;
	}
	
	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeString(this.title);
		dest.writeString(this.url);
		dest.writeString(this.searchType);
		dest.writeByte(this.showHorizontalPB ? (byte) 1 : (byte) 0);
		dest.writeByte(this.showCenterPB ? (byte) 1 : (byte) 0);
		dest.writeByte(this.setBuiltInZoomControls ? (byte) 1 : (byte) 0);
		dest.writeByte(this.setDisplayZoomControls ? (byte) 1 : (byte) 0);
		dest.writeByte(this.setJavaScriptEnabled ? (byte) 1 : (byte) 0);
		dest.writeByte(this.setJavaScriptCanOpenWindowsAutomatically ? (byte) 1 : (byte) 0);
		dest.writeByte(this.setUseWideViewPort ? (byte) 1 : (byte) 0);
		dest.writeByte(this.setLoadWithOverviewMode ? (byte) 1 : (byte) 0);
		dest.writeByte(this.setAppCacheEnabled ? (byte) 1 : (byte) 0);
		dest.writeByte(this.setDatabaseEnabled ? (byte) 1 : (byte) 0);
		dest.writeByte(this.setDomStorageEnabled ? (byte) 1 : (byte) 0);
		dest.writeByte(this.setSupportMultipleWindows ? (byte) 1 : (byte) 0);
		dest.writeByte(this.setSupportZoom ? (byte) 1 : (byte) 0);
		dest.writeByte(this.setGeolocationEnabled ? (byte) 1 : (byte) 0);
		dest.writeInt(this.setCacheMode);
		dest.writeInt(this.setMinimumFontSize);
		dest.writeInt(this.setMixedContentMode);
		dest.writeInt(this.setTextZoom);
		dest.writeInt(this.setLayoutAlgorithm == null ? -1 : this.setLayoutAlgorithm.ordinal());
	}
	
	protected WebSettingsModel(Parcel in) {
		this.title = in.readString();
		this.url = in.readString();
		this.searchType = in.readString();
		this.showHorizontalPB = in.readByte() != 0;
		this.showCenterPB = in.readByte() != 0;
		this.setBuiltInZoomControls = in.readByte() != 0;
		this.setDisplayZoomControls = in.readByte() != 0;
		this.setJavaScriptEnabled = in.readByte() != 0;
		this.setJavaScriptCanOpenWindowsAutomatically = in.readByte() != 0;
		this.setUseWideViewPort = in.readByte() != 0;
		this.setLoadWithOverviewMode = in.readByte() != 0;
		this.setAppCacheEnabled = in.readByte() != 0;
		this.setDatabaseEnabled = in.readByte() != 0;
		this.setDomStorageEnabled = in.readByte() != 0;
		this.setSupportMultipleWindows = in.readByte() != 0;
		this.setSupportZoom = in.readByte() != 0;
		this.setGeolocationEnabled = in.readByte() != 0;
		this.setCacheMode = in.readInt();
		this.setMinimumFontSize = in.readInt();
		this.setMixedContentMode = in.readInt();
		this.setTextZoom = in.readInt();
		int tmpSetLayoutAlgorithm = in.readInt();
		this.setLayoutAlgorithm = tmpSetLayoutAlgorithm == -1 ? null : WebSettings.LayoutAlgorithm.values()[tmpSetLayoutAlgorithm];
	}
	
	public static final Creator<WebSettingsModel> CREATOR = new Creator<WebSettingsModel>() {
		@Override
		public WebSettingsModel createFromParcel(Parcel source) {
			return new WebSettingsModel(source);
		}
		
		@Override
		public WebSettingsModel[] newArray(int size) {
			return new WebSettingsModel[size];
		}
	};
}

设置工具类 WebSettingsUtils 

public class WebSettingsUtils {
	/**
	 * 设置WebSettings中的参数
	 */
	@SuppressLint("SetJavaScriptEnabled")
	public static void setWebSettings(WebSettings webSettings, WebSettingsModel model) {
		//必选的JavaScript
		webSettings.setJavaScriptEnabled(model.setJavaScriptEnabled);//允许js交互
		webSettings.setJavaScriptCanOpenWindowsAutomatically(model.setJavaScriptCanOpenWindowsAutomatically);//让JavaScript自动打开窗口
		
		//缩放
		webSettings.setSupportZoom(model.setSupportZoom);//默认值
		webSettings.setBuiltInZoomControls(model.setBuiltInZoomControls); //使用内置的缩放机制,设为false时setDisplayZoomControls无效
		webSettings.setDisplayZoomControls(model.setDisplayZoomControls);//使用内置的缩放机制时是否展示缩放控件
		
		//文字
		webSettings.setTextZoom(model.setTextZoom);//设置页面上的文本缩放百分比,默认100
		webSettings.setMinimumFontSize(model.setMinimumFontSize);//设置最小的字号,默认为8。某些情况下设置这个比设置setTextZoom更友好
		
		//布局相关
		webSettings.setUseWideViewPort(model.setUseWideViewPort);//重要!布局的宽度总是与WebView控件上的设备无关像素宽度一致
		webSettings.setLoadWithOverviewMode(model.setLoadWithOverviewMode);//允许缩小内容以适应屏幕宽度
		webSettings.setLayoutAlgorithm(model.setLayoutAlgorithm);//设置布局类型,会引起WebView重新布局
		//默认值NARROW_COLUMNS(适应内容大小),SINGLE_COLUMN(适应屏幕,内容将自动缩放)
		
		//缓存
		webSettings.setAppCacheEnabled(model.setAppCacheEnabled);//应用缓存API可用
		webSettings.setCacheMode(model.setCacheMode);//使用缓存的方式,默认值LOAD_DEFAULT,LOAD_NO_CACHE
		
		//其他
		webSettings.setDatabaseEnabled(model.setDatabaseEnabled);//数据库存储API可用
		webSettings.setDomStorageEnabled(model.setDomStorageEnabled);//DOM存储API可用
		webSettings.setSupportMultipleWindows(model.setSupportMultipleWindows);//支持多窗口
		webSettings.setGeolocationEnabled(model.setGeolocationEnabled);//定位可用。需要有定位权限
		// webview从5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启。
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) webSettings.setMixedContentMode(model.setMixedContentMode);
	}
	
	@SuppressLint("SetJavaScriptEnabled")
	public static void setWebSettings(WebSettings webSettings) {
		//必选的JavaScript
		webSettings.setJavaScriptEnabled(true);//允许js交互
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);//让JavaScript自动打开窗口
		
		//缩放
		webSettings.setSupportZoom(true);//默认值
		webSettings.setBuiltInZoomControls(true); //使用内置的缩放机制,设为false时setDisplayZoomControls无效
		webSettings.setDisplayZoomControls(false);//使用内置的缩放机制时是否展示缩放控件
		webSettings.setTextZoom(100);//设置页面上的文本缩放百分比,默认100
		webSettings.setMinimumFontSize(8);//设置最小的字号,默认为8。某些情况下设置这个比设置setTextZoom更友好
		
		//布局相关
		webSettings.setUseWideViewPort(true);//重要!布局的宽度总是与WebView控件上的设备无关像素宽度一致
		webSettings.setLoadWithOverviewMode(true);//允许缩小内容以适应屏幕宽度
		webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//设置布局类型,会引起WebView重新布局
		//默认值NARROW_COLUMNS(适应内容大小),SINGLE_COLUMN(适应屏幕,内容将自动缩放)
		
		//缓存
		webSettings.setAppCacheEnabled(true);//应用缓存API可用
		webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//使用缓存的方式,默认值LOAD_DEFAULT,LOAD_NO_CACHE
		
		//其他
		webSettings.setGeolocationEnabled(true);//默认值
		webSettings.setDatabaseEnabled(true);//数据库存储API可用
		webSettings.setDomStorageEnabled(true);//DOM存储API可用
		webSettings.setSupportMultipleWindows(true);//支持多窗口。如果设置为true,主程序要实现onCreateWindow
	}
}

示例 Activity

public class WebViewTestActivity extends ListActivity {

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		String[] array = {"参数传为null,这时使用的是WebViewModel.Builder中的默认设置",
				"搜索白乾涛(是否显示ProgressBar:showProgressBar)",
				"使用GitHub搜索指定的项目:searchType",
				"设置WebSettings的支持缩放:setBuiltInZoomControls和setDisplayZoomControls",
				"设置WebSettings的显示模式:setUseWideViewPort和setLoadWithOverviewMode",
				"设置WebSettings的字体缩放:setTextZoom",
				"设置WebSettings的最小字体:setMinimumFontSize",};
		setListAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, new ArrayList<>(Arrays.asList(array))));
	}

	private boolean b;

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		b = !b;
		switch (position) {
			case 0:
				WebViewActivity.start(this, null);
				break;
			case 1:
				WebViewActivity.start(this, WebViewModel.newBuilder()
						.title("是否显示ProgressBar")
						.showProgressBar(b)
						.url("白乾涛").build());
				break;
			case 2:
				WebViewActivity.start(this, WebViewModel.newBuilder()
						.title("使用GitHub搜索指定的项目")
						.searchType("github")
						.url("MyViews").build());
				break;
			case 3:
				WebViewActivity.start(this, WebViewModel.newBuilder()
						.title("电影天堂")
						.setBuiltInZoomControls(b)
						.setDisplayZoomControls(false)//是否展示缩放控件。这个控件非常丑,不要显示!
						.url("http://www.dy2018.com/").build());
				break;
			case 4:
				WebViewActivity.start(this, WebViewModel.newBuilder()
						.title("电影天堂")
						.setUseWideViewPort(true)
						.setLoadWithOverviewMode(b)//setUseWideViewPort为true时才有效
						.url("http://www.dy2018.com/").build());
				break;
			case 5:
				WebViewActivity.start(this, WebViewModel.newBuilder()
						.title("电影天堂")
						.setUseWideViewPort(true)
						.setLoadWithOverviewMode(true)
						.setTextZoom(50 + (int) (new Random().nextFloat() * 4 * 100))//50-450
						.url("https://open.weixin.qq.com/cgi-bin/frame?t=news/protocol_developer_tmpl").build());
				break;
			case 6:
				WebViewActivity.start(this, WebViewModel.newBuilder()
						.title("电影天堂")
						.setUseWideViewPort(true)
						.setLoadWithOverviewMode(true)
						.setMinimumFontSize(10 + new Random().nextInt(50))//10-60
						.url("https://open.weixin.qq.com/cgi-bin/frame?t=news/protocol_developer_tmpl").build());
				break;
		}
	}
}
2017-7-19




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值