下面列出了android.webkit.WebSettings#setDefaultTextEncodingName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void setWebView()
{
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);//如果访问的页面中要与Javascript交互,则webview必须设置支持Javascript
webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
webSettings.setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。
webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放
webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
webSettings.setAllowFileAccess(true); //设置可以访问文件
webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式
webSettings.setDomStorageEnabled(true);
mWebView.setWebViewClient(new WebViewClient());
}
@SuppressLint("SetJavaScriptEnabled")
private void initWebSettings() {
WebSettings settings = this.mWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
settings.setSupportZoom(false);
settings.setDisplayZoomControls(false);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
settings.supportMultipleWindows();
settings.setSupportMultipleWindows(true);
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled(true);
settings.setAppCacheEnabled(true);
settings.setAppCachePath(this.mWebView.getContext().getCacheDir().getAbsolutePath());
settings.setAllowFileAccess(true);
settings.setLoadsImagesAutomatically(true);
settings.setDefaultTextEncodingName("UTF-8");
}
private void setContents(View rootView) {
String str;
StringBuilder buf = new StringBuilder("<pre>");
try {
InputStream is = getActivity().getAssets().open("LICENSE-2.0.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(is));
while ((str = in.readLine()) != null) {
buf.append(str + "<br />");
}
in.close();
} catch (IOException e) {
return;
}
WebView webView = (WebView) rootView.findViewById(R.id.webview);
buf.append("</pre>");
String encoding = "utf-8";
WebSettings settings = webView.getSettings();
settings.setDefaultTextEncodingName(encoding);
webView.loadDataWithBaseURL(null, buf.toString(), "text/html", encoding, null);
}
private void buildSetting(WebView webView) {
webView.clearCache(true);
webView.clearHistory();
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setDefaultTextEncodingName("utf-8");// 避免中文乱码
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
webSettings.setJavaScriptEnabled(true);
webSettings.setNeedInitialFocus(false);
// webSettings.setDatabaseEnabled(true);
webSettings.setDomStorageEnabled(true);
// webSettings.setBlockNetworkLoads(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);//1、提高渲染的优先级
// webSettings.setBlockNetworkImage(true);//把图片加载放在最后来加载渲染
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setSupportZoom(false);
}
@SuppressWarnings("deprecation")
@SuppressLint({"SetJavaScriptEnabled", "NewApi", "ObsoleteSdkInt"})
public void initializeSettings(WebSettings settings) {
settings.setJavaScriptEnabled(true);
addJavascriptInterface(new JavaScriptUtil(), "DappJsBridge");
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
settings.setAppCacheMaxSize(Long.MAX_VALUE);
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
settings.setEnableSmoothTransition(true);
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
settings.setMediaPlaybackRequiresUserGesture(true);
}
WebView.setWebContentsDebuggingEnabled(true);
settings.setDomStorageEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setAppCacheEnabled(true);
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
settings.setLoadsImagesAutomatically(true);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
settings.setDatabaseEnabled(true);
settings.setDisplayZoomControls(false);
settings.setAllowContentAccess(true);
settings.setAllowFileAccess(false);
settings.setRenderPriority(WebSettings.RenderPriority.LOW);
setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
settings.setDefaultTextEncodingName("utf-8");
settings.setAllowFileAccessFromFileURLs(false);
settings.setAllowUniversalAccessFromFileURLs(false);
// 特别注意:5.1以上默认禁止了https和http混用,以下方式是开启
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
}
}
public void initializeWebView(WebView view) {
String text = loadTextFile(R.raw.about_body);
String version = PackageHelper.getVersionName(getActivity());
String changelog = loadTextFile(R.raw.changelog);
String css = loadTextFile(R.raw.about_css);
text = String.format(text, version, changelog, css);
WebSettings settings = view.getSettings();
settings.setDefaultTextEncodingName("utf-8");
view.loadDataWithBaseURL(null, text, "text/html", "UTF-8", null);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sky_activity_about);
setHeader("房贷计算器", true);
WebView webView = (WebView) findViewById(R.id.web_app_view);
WebSettings webSettings = webView.getSettings();
webSettings.setDefaultTextEncodingName("UTF-8");
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setSupportZoom(true);
webView.loadUrl("file:///android_asset/calculator/calculator.html");
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setSupportActionBar(R.id.browser_toolbar);
final String url = getIntent().getStringExtra(EXTRA_URL);
if (TextUtils.isEmpty(url)) {
finish();
return;
}
setTitle("");
mVContent = findViewById(R.id.browser_wb_content);
WebSettings webSettings = mVContent.getSettings();
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setSupportZoom(true);
webSettings.setNeedInitialFocus(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setBlockNetworkImage(false);
webSettings.setLoadsImagesAutomatically(true);
webSettings.setDisplayZoomControls(false);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
if (Build.VERSION.SDK_INT >= 21) {
webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
webSettings.setDefaultTextEncodingName("utf-8");
mVContent.setWebViewClient(new PowerfulWebView.StateWebViewClient());
mVContent.setOnTitleListener(this);
mVContent.loadUrl(url);
}
private void initWebView() {
WebSettings ws = webView.getSettings();
//网页内容的宽度是否可以大于WebView控件的宽度
ws.setLoadWithOverviewMode(false);
//保存表单数据
ws.setSaveFormData(true);
//是否应该支持使用其屏幕缩放控件和手势缩放
ws.setSupportZoom(true);
ws.setBuiltInZoomControls(true);
ws.setDisplayZoomControls(false);
//启动应用缓存
ws.setAppCacheEnabled(true);
//设置缓存模式
ws.setCacheMode(WebSettings.LOAD_DEFAULT);
//启用JavaScript执行,默认的是false
ws.setJavaScriptEnabled(true);
//页面加载后之后再放开图片
ws.setBlockNetworkImage(false);
//使用localStorage则必须打开
ws.setDomStorageEnabled(true);
//设置文字的格式
ws.setDefaultTextEncodingName("UTF-8");
//WebView5.0开始默认不允许混合模式,https中不能加载http资源,需要设置开启
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
//设置字体默认缩放大小(改变网页字体大小,setTextSize API14被弃用)
ws.setTextZoom(100);
webView.setWebChromeClient(new MyWebChromeClient(this));
webView.setWebViewClient(new MyWebViewClient(this));
webView.addJavascriptInterface(new ImageClickInterface(this), "injectedObject");
}
public static void a(WebSettings webSettings) {
webSettings.setJavaScriptEnabled(true);
webSettings.setDefaultTextEncodingName(z[86]);
webSettings.setSupportZoom(true);
webSettings.setCacheMode(2);
webSettings.setSaveFormData(false);
webSettings.setSavePassword(false);
}
@SuppressLint("JavascriptInterface")
private void initWebView() {
// Settings
WebSettings settings = webView.getSettings();
settings.setDefaultTextEncodingName("GBK");
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
settings.setGeolocationEnabled(true);
// settings.setDisplayZoomControls(false);
settings.setBuiltInZoomControls(true);
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
settings.setDatabaseEnabled(true);
settings.setAppCacheEnabled(true);
settings.setAppCachePath(this.getContext().getCacheDir().getAbsolutePath());
settings.setDisplayZoomControls(false);
webView.requestFocus();
webView.setWebViewClient(new WebViewClient() {
});
webView.setWebChromeClient(new WebChromeClient() {
});
}
private void initSettings() {
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(false);
webSettings.setDisplayZoomControls(false);
webSettings.setDefaultTextEncodingName("UTF-8");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager cookieManager = CookieManager.getInstance();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
webSettings.setMixedContentMode(
WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
}
}
protected void configWebView() {
mWebView = new WebView(getApplicationContext());
mWebViewContainer.addView(mWebView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDefaultTextEncodingName("UTF-8");
settings.setSupportZoom(false);
settings.setPluginState(WebSettings.PluginState.ON);
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
}
@SuppressLint("SetJavaScriptEnabled") private void initView(@Nullable AttributeSet attrs) {
if (isInEditMode()) return;
if (attrs != null) {
TypedArray tp = getContext().obtainStyledAttributes(attrs, R.styleable.PrettifyWebView);
try {
int color = tp.getColor(R.styleable.PrettifyWebView_webview_background, ViewHelper.getWindowBackground(getContext()));
setBackgroundColor(color);
} finally {
tp.recycle();
}
}
setWebChromeClient(new ChromeClient());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
setWebViewClient(new WebClient());
} else {
setWebViewClient(new WebClientCompat());
}
WebSettings settings = getSettings();
settings.setJavaScriptEnabled(true);
settings.setAppCachePath(getContext().getCacheDir().getPath());
settings.setAppCacheEnabled(true);
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
settings.setDefaultTextEncodingName("utf-8");
settings.setLoadsImagesAutomatically(true);
settings.setBlockNetworkImage(false);
setOnLongClickListener((view) -> {
WebView.HitTestResult result = getHitTestResult();
if (hitLinkResult(result) && !InputHelper.isEmpty(result.getExtra())) {
AppHelper.copyToClipboard(getContext(), result.getExtra());
return true;
}
return false;
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_html_viewer);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
mWebView = findViewById(R.id.webview);
mLoading = findViewById(R.id.loading);
mWebView.setWebChromeClient(new ChromeClient());
mWebView.setWebViewClient(new ViewClient());
WebSettings s = mWebView.getSettings();
s.setUseWideViewPort(true);
s.setSupportZoom(true);
s.setBuiltInZoomControls(true);
s.setDisplayZoomControls(false);
s.setSavePassword(false);
s.setSaveFormData(false);
s.setBlockNetworkLoads(true);
// Javascript is purposely disabled, so that nothing can be
// automatically run.
s.setJavaScriptEnabled(false);
s.setDefaultTextEncodingName("utf-8");
final Intent intent = getIntent();
if (intent.hasExtra(Intent.EXTRA_TITLE)) {
setTitle(intent.getStringExtra(Intent.EXTRA_TITLE));
}
mWebView.loadUrl(String.valueOf(intent.getData()));
}
@Override
public void setDefaultTextEncodingName(WebSettings settings, String encoding) {
settings.setDefaultTextEncodingName(encoding);
}
public EditAreaView(Context context, AttributeSet attrs) {
super(context, attrs);
if (L.debug) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setWebContentsDebuggingEnabled(true);
}
}
setLongClickable(false);
setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
return true;
}
});
WebSettings ws = getSettings();
ws.setDefaultZoom(WebSettings.ZoomDensity.FAR);
ws.setAllowContentAccess(true);
ws.setAllowFileAccess(true);
ws.setBuiltInZoomControls(false);
ws.setDefaultTextEncodingName("utf-8");
ws.setDisplayZoomControls(false);
ws.setSupportZoom(false);
ws.setLoadWithOverviewMode(false);
ws.setJavaScriptEnabled(true);
ws.setAppCacheEnabled(false);
ws.setDomStorageEnabled(true);
ws.setAppCacheMaxSize(1024*1024*80);
ws.setAppCachePath(context.getCacheDir().getPath());
// ws.setAllowFileAccess(true);
ws.setCacheMode(WebSettings.LOAD_DEFAULT);
addJavascriptInterface(new JavascriptApi(), "AndroidEditor");
setWebViewClient(new EditorViewClient());
setWebChromeClient(new EditorViewChromeClient());
pref = Pref.getInstance(getContext());
ThemeList.Theme theme = pref.getThemeInfo();
boolean isDark = false;
if (theme != null) {
isDark = theme.isDark;
}
String html = null;
try {
InputStream is = getContext().getAssets().open("editor.html");
html = IOUtils.readFile(is, "utf-8");
is.close();
} catch (Exception e) {
L.e(e);
UIUtils.toast(getContext(), R.string.editor_create_unknown_exception);
return;
}
if (!isDark)
html = html.replaceAll("<\\!\\-\\-\\{DARK\\-START\\}\\-\\->[\\w\\W]+?<\\!\\-\\-\\{DARK\\-END\\}\\-\\->", "");
loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", "file:///android_asset/");
//fix dark theme background spark
setBackgroundColor(Color.TRANSPARENT);
pref.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(null, Pref.KEY_FONT_SIZE);
onSharedPreferenceChanged(null, Pref.KEY_CURSOR_WIDTH);
onSharedPreferenceChanged(null, Pref.KEY_SHOW_LINE_NUMBER);
onSharedPreferenceChanged(null, Pref.KEY_WORD_WRAP);
onSharedPreferenceChanged(null, Pref.KEY_SHOW_WHITESPACE);
onSharedPreferenceChanged(null, Pref.KEY_TAB_SIZE);
onSharedPreferenceChanged(null, Pref.KEY_AUTO_INDENT);
onSharedPreferenceChanged(null, Pref.KEY_AUTO_CAPITALIZE);
onSharedPreferenceChanged(null, Pref.KEY_INSERT_SPACE_FOR_TAB);
onSharedPreferenceChanged(null, Pref.KEY_THEME);
onSharedPreferenceChanged(null, Pref.KEY_TOUCH_TO_ADJUST_TEXT_SIZE);
enableHighlight(pref.isHighlight());
setReadOnly(pref.isReadOnly());
}
private void setWebView(WebView webView){
WebSettings settings = webView.getSettings();
settings.setDefaultTextEncodingName(KEY_UTF_8);
settings.setJavaScriptEnabled(true);
}
@SuppressWarnings("deprecation")
@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
public void initializeSettings(WebSettings settings, Context context) {
//setPageCacheCapacity2(settings);
if (API < 18) {
settings.setAppCacheMaxSize(Long.MAX_VALUE);
}
if (API < 17) {
settings.setEnableSmoothTransition(true);
}
if (API > 16) {
settings.setMediaPlaybackRequiresUserGesture(true);
}
if (API >= Build.VERSION_CODES.LOLLIPOP && !mBrowserController.isIncognito()) {
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
} else if (API >= Build.VERSION_CODES.LOLLIPOP) {
// We're in Incognito mode, reject
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
}
settings.setDomStorageEnabled(true);
settings.setAppCacheEnabled(true);
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
settings.setDatabaseEnabled(true);
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
settings.setAllowContentAccess(true);
settings.setAllowFileAccess(true);
settings.setDefaultTextEncodingName("utf-8");
if (API > 16) {
settings.setAllowFileAccessFromFileURLs(false);
settings.setAllowUniversalAccessFromFileURLs(false);
}
settings.setAppCachePath(context.getDir("appcache", 0).getPath());
settings.setGeolocationDatabasePath(context.getDir("geolocation", 0).getPath());
if (API < Build.VERSION_CODES.KITKAT) {
settings.setDatabasePath(context.getDir("databases", 0).getPath());
}
}
public boolean loadToWebView(WebView v) {
myWebView = v;
v.setWebViewClient(new WebClient());
WebSettings webSettings = v.getSettings();
webSettings.setDefaultTextEncodingName("UTF-8");
myLoadingArchive = true;
try {
// Find the first ArchiveResource in myDoc, should be <ArchiveResource>
Element ar = (Element) myDoc.getDocumentElement().getFirstChild().getFirstChild();
byte b[] = getElBytes(ar, "data");
// Find out the web page charset encoding
String charset = null;
String topHtml = new String(b).toLowerCase();
int n1 = topHtml.indexOf("<meta http-equiv=\"content-type\"");
if (n1 > -1) {
int n2 = topHtml.indexOf('>', n1);
if (n2 > -1) {
String tag = topHtml.substring(n1, n2);
n1 = tag.indexOf("charset");
if (n1 > -1) {
tag = tag.substring(n1);
n1 = tag.indexOf('=');
if (n1 > -1) {
tag = tag.substring(n1 + 1);
tag = tag.trim();
n1 = tag.indexOf('\"');
if (n1 < 0)
n1 = tag.indexOf('\'');
if (n1 > -1) {
charset = tag.substring(0, n1).trim();
}
}
}
}
}
if (charset != null)
topHtml = new String(b, charset);
else {
topHtml = new String(b);
/*
* CharsetMatch match = new CharsetDetector().setText(b).detect();
* if (match != null)
* try {
* Lt.d("Guessed enc: " + match.getName() + " conf: " + match.getConfidence());
* topHtml = new String(b, match.getName());
* } catch (UnsupportedEncodingException ue) {
* topHtml = new String(b);
* }
*/
}
String baseUrl = new String(getElBytes(ar, "url"));
v.loadDataWithBaseURL(baseUrl, topHtml, "text/html", "UTF-8", null);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}