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方法,灰色代表廢棄的方法。
- setAllowContentAccess(boolean allow) Enables or disables content URL access within WebView. The default is enabled.
- 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.
- 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.
- 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.
- setAppCacheEnabled(boolean flag) Sets whether the Application Caches API should be enabled. The default is false.
-
setAppCacheMaxSize(long appCacheMaxSize) This method was deprecated in API level 18. In future quota will be managed automatically. The default size is MAX_VALUE. - setAppCachePath(String appCachePath) Sets the path to the Application Caches files. This method should only be called once: repeated calls are ignored.
- 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.
- 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.
- setBuiltInZoomControls(boolean enabled) Sets whether the WebView should use its built-in zoom mechanisms. The default is false.
- setCacheMode(int mode) Overrides the way the cache is used. The default value is LOAD_DEFAULT.
- setCursiveFontFamily(String font) Sets the cursive font family name. The default is "cursive".
- setDatabaseEnabled(boolean flag) Sets whether the database storage API is enabled. The default value is false.
-
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. - setDefaultFixedFontSize(int size) Sets the default fixed font size. The default is 16.
- setDefaultFontSize(int size) Sets the default font size. The default is 16.
- setDefaultTextEncodingName(String encoding) Sets the default text encoding name to use when decoding html pages. The default is "UTF-8".
-
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. - setDisabledActionModeMenuItems(int menuItems) Disables the action mode menu items according to menuItems flag.
- setDisplayZoomControls(boolean enabled) Sets whether the WebView should display on-screen zoom controls when using the built-in zoom mechanisms. The default is true.
- setDomStorageEnabled(boolean flag) Sets whether the DOM storage API is enabled. The default value is false.
-
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. - setFantasyFontFamily(String font) Sets the fantasy font family name. The default is "fantasy".
- setFixedFontFamily(String font) Sets the fixed font family name. The default is "monospace".
-
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. - setGeolocationEnabled(boolean flag) Sets whether Geolocation is enabled. The default is true.
- setJavaScriptCanOpenWindowsAutomatically(boolean flag) Tells JavaScript to open windows automatically. The default is false.
- setJavaScriptEnabled(boolean flag) Tells the WebView to enable JavaScript execution. The default is false.
- setLayoutAlgorithm(WebSettings.LayoutAlgorithm l) Sets the underlying layout algorithm. The default is NARROW_COLUMNS.
-
setLightTouchEnabled(boolean enabled) This method was deprecated in API level 18. From JELLY_BEAN this setting is obsolete and has no effect. - 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.
- setLoadsImagesAutomatically(boolean flag) Sets whether the WebView should load image resources. The default is true.
- setMediaPlaybackRequiresUserGesture(boolean require) Sets whether the WebView requires a user gesture to play media. The default is true.
- setMinimumFontSize(int size) Sets the minimum font size. The default is 8.
- setMinimumLogicalFontSize(int size) Sets the minimum logical font size. The default is 8.
- 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.
- 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.
- setOffscreenPreRaster(boolean enabled) Sets whether this WebView should raster tiles when it is offscreen but attached to a window. The default value is false.
-
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. -
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. - setSafeBrowsingEnabled(boolean enabled) Sets whether Safe Browsing is enabled. Safe browsing is disabled by default.
- setSansSerifFontFamily(String font) Sets the sans-serif font family name. The default is "sans-serif".
- 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.
-
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. - setSerifFontFamily(String font) Sets the serif font family name. The default is "sans-serif".
- setStandardFontFamily(String font) Sets the standard font family name. The default is "sans-serif".
- setSupportMultipleWindows(boolean support) Sets whether the WebView whether supports multiple windows. The default is false.
- setSupportZoom(boolean support) Sets whether the WebView should support zooming using its on-screen zoom controls and gestures. The default is true.
-
setTextSize(WebSettings.TextSize t) This method was deprecated in API level 14. Use setTextZoom(int) instead. The default is NORMAL. - setTextZoom(int textZoom) Sets the text zoom of the page in percent. The default is 100.
- setUseWideViewPort(boolean use) Sets whether the WebView should enable support for the "viewport" HTML meta tag or should use a wide viewport.
- 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 翻譯
- setAllowContentAccess (boolean allow):是否允許在WebView中訪問內容URL(Content Url),默認允許。內容Url訪問允許WebView從安裝在系統中的內容提供者載入內容。
- setAllowFileAccess (boolean allow):是否允許訪問文件,默認允許。注意,這里只是允許或禁止對文件系統的訪問,Assets 和 resources 文件使用file:///android_asset和file:///android_res仍是可訪問的。
- setAllowFileAccessFromFileURLs (boolean flag):是否允許運行在一個URL環境(the context of a file scheme URL)中的JavaScript訪問來自其他URL環境的內容,為了保證安全,應該不允許。也請注意,這項設置只影響對file schema 資源的javascript訪問,其他形式的訪問,例如來自圖片HTML單元的訪問不受影響。為了防止相同的域策略(same domain policy)對ICE_CREAM_SANDWICH以及更老機型的侵害,應該顯式地設置此值為false。
- 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
- setAppCacheEnabled (boolean flag):應用緩存API是否可用,默認值false, 結合setAppCachePath(String)使用。
- setAppCachePath(String):設置應用緩存文件的路徑。為了讓應用緩存API可用,此方法必須傳入一個應用可寫的路徑。該方法只會執行一次,重復調用會被忽略。
- setAppCacheMaxSize (long appCacheMaxSize):已廢棄。設置應用緩存內容的最大值。所傳值會被近似為數據庫支持的最近似值,因此這是一個指示值,而不是一個固定值。所傳值若小於數據庫大小不會讓數據庫調整大小。默認值是MAX_VALUE,建議將默認值設置為最大值。
- setBlockNetworkImage (boolean flag):是否禁止從網絡(通過http和https URI schemes訪問的資源)下載圖片資源,默認值為false。注意,除非getLoadsImagesAutomatically()返回true,否則該方法無效。還請注意,即使此項設置為false,使用setBlockNetworkLoads(boolean)禁止所有網絡加載也會阻止網絡圖片的加載。當此項設置的值從true變為false,WebView當前顯示的內容所引用的網絡圖片資源會自動獲取。
- setBlockNetworkLoads (boolean flag):是否禁止從網絡下載數據,如果app有INTERNET權限,默認值為false,否則默認為true。使用setBlockNetworkImage(boolean) 只會禁止圖片資源的加載。注意此值由true變為false,當前WebView展示的內容所引用的網絡資源不會自動加載,直到調用了重載。如果APP沒有INTERNET權限,設置此值為false會拋出SecurityException。
- setBuiltInZoomControls (boolean enabled):是否使用內置的縮放機制。內置的縮放機制包括屏幕上的縮放控件(浮於WebView內容之上)和縮放手勢的運用。通過setDisplayZoomControls(boolean)可以控制是否顯示這些控件,默認值為false。
- setCacheMode (int mode):重寫使用緩存的方式,默認值LOAD_DEFAULT。緩存的使用方式基於導航類型,正常的頁面加載,檢測緩存,需要時緩存內容復現。導航返回時,內容不會復現,只有內容會從緩存盤中恢復。該方法允許客戶端通過指定LOAD_DEFAULT, LOAD_CACHE_ELSE_NETWORK, LOAD_NO_CACHE or LOAD_CACHE_ONLY的其中一項來重寫其行為。
- setCursiveFontFamily (String font):設置WebView字體庫字體,默認“cursive”
- setDatabaseEnabled (boolean flag):數據庫存儲API是否可用,默認值false。如何正確設置數據存儲API參見setDatabasePath(String)。該設置對同一進程中的所有WebView實例均有效。注意,只能在當前進程的任意WebView加載頁面之前修改此項,因為此節點之后WebView的實現類可能會忽略該項設置的改變。
- setDatabasePath (String databasePath):已廢棄,數據庫路徑由實現(implementation)管理,調用此方法無效。 設置數據庫的存儲路徑,為了保證數據庫正確運行,該方法必須使用一個應用可寫的路徑。此方法只能執行一次,重復調用會被忽略。
- setDefaultFixedFontSize (int size):設置默認固定的字體大小,默認為16,可取值1到72
- setDefaultFontSize (int size):設置默認的字體大小,默認16,可取值1到72
- setDefaultTextEncodingName (String encoding):設置默認的字符編碼集,默認”UTF-8”.
- setDefaultZoom (WebSettings.ZoomDensity zoom):已廢棄。設置默認的縮放密度,必須在UI線程調用,默認值MEDIUM.該項設置在新應用中不推薦使用。如果WebView用於展示手機頁面,可以通過調整頁面的’meta viewport’ 標記中的’width’ 和 ‘initial-scale’屬性實現預期效果,對於漏用標記的頁面,可以使用setInitialScale(int)和setUseWideViewPort(boolean) .
- setDisabledActionModeMenuItems(int menuItems) 根據menuItems標志禁用"動作模式菜單項 ActionModeMenuItems"。
- setDisplayZoomControls (boolean enabled):使用內置的縮放機制時是否展示縮放控件,默認值true。參見setBuiltInZoomControls(boolean).
- setDomStorageEnabled (boolean flag):DOM存儲API是否可用,默認false。
- setEnableSmoothTransition (boolean enable):已廢棄,將來會成為空操作(no-op),設置當panning或者縮放或者持有當前WebView的window沒有焦點時是否允許其光滑過渡,若為true,WebView會選擇一個性能最大化的解決方案。例如過渡時WebView的內容可能不更新。若為false,WebView會保持精度(fidelity),默認值false。
- setFantasyFontFamily (String font):設置fantasy字體集(font family)的名字默認為“fantasy”
- setFixedFontFamily (String font):設置固定的字體集的名字,默認為”monospace”。
- setGeolocationDatabasePath (String databasePath):定位數據庫的保存路徑,為了確保定位權限和緩存位置的持久化,該方法應該傳入一個應用可寫的路徑。
- 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