Android中WebView国际化多语言刷新问题
前言:
做过国际化多语言开发的同学,相信大家都会遇到WebView的多语言刷新问题,本来普通的界面根据语言是否改变,监听Application的onConfigurationChanged方法就可以实现多语言切换,但是WebView根据实际需求和开发环境的不同,光加上这些监听和方法在还有缓存的情况下切换语言不会立即生效。 说一种特殊情况,我们目前项目的售后服务界面是以post请求的方式加载h5界面的,不是直接在网页地址后面拼接的语言参数,所以当切换语言之后,即使重启app界面重新加载也不会立即刷新语言,多种尝试之后才得以解决webView的多语言切换问题.
1.第1种方法:
在结束界面时清除缓存和历史记录,销毁webview,具体代码如下:
scss
@Override
protected void onDestroy() {
dismissLoadingDialog();
if (mWebView != null) {
mWebView.clearFormData();
mWebView.clearHistory();
mWebView.clearCache(true);
mWebView.getSettings().setDatabasePath(null);
mWebView.getSettings().setAppCachePath(null);
mWebView.stopLoading();
mWebView.removeAllViews();
ViewParent parent = mWebView.getParent();
if (parent != null) {
((ViewGroup) parent).removeView(mWebView);
}
mWebView.clearView();
mWebView.destroy();
mWebView = null;
}
super.onDestroy();
}
从上面的代码可以看出,webview缓存清除的非常彻底,而且webview也被销毁了,但是清理完成后发现并没用,需要打开2次界面切换语言才会生效,这是一个非常不好的体验,是一个很严重的bug.
2.第2种方法:
在网页加载完成并且是售后服务界面时,强行刷新界面,代码如下:
typescript
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
dismissLoadingDialog();
mWebView.setVisibility(View.VISIBLE);
if (!TextUtils.isEmpty(url) && url.contains("listAftersales")) {
UserData userData = GreenDaoManager.getInstance().getUserData();
if (userData != null) {
mWebView.loadUrl("javascript:getUserIdAndLan(" + "'" + userData.getUserId() + "'"
+ " , " + "'" + LanguageUtils.getServiceLanguage() + "'" + ")");
if (isRefresh) {
mWebView.reload();
isRefresh = false;
}
}
}
}
加完之后重新跑起来,发现切换语言后界面果然重新刷新了,但是这样又发现一个严重问题,就是点击网页上的售后服务其他界面或者按钮也会刷新界面,这样肯定还是没有解决问题.
3.第3次尝试:
加了一个是否刷新的布尔值参数,判断是否需要刷新,当isRefresh=true并且是售后服务界面时才刷新.
在initView时把值置为true,这样每次创建并加载网页时,是否需要刷新值为true.
ini
prvalte boolean isRefresh = fasle;
@Override
protected void initView(Bundle savedInstanceState) {
showLoadingDialog(false);
mBackBt = findViewById(R.id.webview_back_iv);
mWebView = findViewById(R.id.webview);
mTitleTv = findViewById(R.id.webview_tilte);
// mWebView.addJavascriptInterface(new Whatever(),"getUserInfo");
isRefresh = true;
}
在网页加载完成后,判断是否是售后服务界面且需要刷新时才强制刷新界面.在刷新之后,把是否可刷新置为false,这样即使发生屏幕旋转等等也不会出现多次强制刷新问题.
typescript
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
dismissLoadingDialog();
mWebView.setVisibility(View.VISIBLE);
if (!TextUtils.isEmpty(url) && url.contains("listAftersales")) {
UserData userData = GreenDaoManager.getInstance().getUserData();
if (userData != null) {
mWebView.loadUrl("javascript:getUserIdAndLan(" + "'" + userData.getUserId() + "'"
+ " , " + "'" + LanguageUtils.getServiceLanguage() + "'" + ")");
if (isRefresh) {
mWebView.reload();
isRefresh = false;
}
}
}
}
加上上面的方法后,重新运行,尝试了切换各种语言中、英、日、德等,发现每次切换语言后,进入到售后服务界面都会立即刷新成相对应的语言,至此,webViewd的多语言问题,得到解决。
4.LanguaeUtils工具类如下:
kotlin
package com.powervision.UIKit.utils;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import com.powervision.UIKit.BaseApplication;
import com.powervision.lib_common.utils.LogUtils;
import java.util.Locale;
/**
* 语言工具类
*/
public class LanguageUtils {
/**
* 获取本机语言
* zh-中文 en-英文 ar-阿拉伯语 cs-捷克语 da-丹麦语 de-德语 es-西班牙语 fi-芬兰语
* fr-法语 hu-匈牙利语 id-印尼语 it-意大利语 ja-日语 ka-乔治亚 ko-韩语 mn-蒙语 nl-荷兰语
* pl-波兰语 pt-葡萄牙语 bx-巴西语 ro-罗马尼亚语 ru-俄罗斯语 sk-斯洛伐克语
* sq-阿尔巴尼亚语 sv-瑞典语 te-泰国语 tr-土耳其语 vi-越南语
*
* @return
*/
public static String getLanguage() {
Locale locale = BaseApplication.getInstanceApp().getResources().getConfiguration().locale;
String language = locale.getLanguage();
if (language.endsWith("zh")) {
return "zh";//中文
} else if (language.endsWith("en")) {
return "en";//英文
} else if (language.endsWith("ar")) {
return "ar";//阿拉伯语
} else if (language.endsWith("cs")) {
return "cs";//cs-捷克语
} else if (language.endsWith("da")) {
return "da";//da-丹麦语
} else if (language.endsWith("de")) {
return "de";//de-德语
} else if (language.endsWith("es")) {
return "es";//es-西班牙语
} else if (language.endsWith("fi")) {
return "fi";//fi-芬兰语
} else if (language.endsWith("fr")) {
return "fr";//fr-法语
} else if (language.endsWith("hu")) {
return "hu";//hu-匈牙利语
} else if (language.endsWith("id")) {
return "id";//id-印尼语
} else if (language.endsWith("it")) {
return "it";//it-意大利语
} else if (language.endsWith("ja")) {
return "ja";//ja-日语
} else if (language.endsWith("ka")) {
return "ka";//ka-乔治亚
} else if (language.endsWith("ko")) {
return "ko";//ko-韩语
} else if (language.endsWith("mn")) {
return "mn";//mn-蒙语
} else if (language.endsWith("nl")) {
return "nl";//nl-荷兰语
} else if (language.endsWith("pl")) {
return "pl";//pl-波兰语
} else if (language.endsWith("pt")) {
return "pt";//pt-葡萄牙语
} else if (language.endsWith("bx")) {
return "bx";//bx-巴西语
} else if (language.endsWith("ro")) {
return "ro";//ro-罗马尼亚语
} else if (language.endsWith("pt")) {
return "pt";//pt-葡萄牙语
} else if (language.endsWith("ru")) {
return "ru";//ru-俄罗斯语
} else if (language.endsWith("sk")) {
return "sk";//sk-斯洛伐克语
} else if (language.endsWith("sq")) {
return "sq";//sq-阿尔巴尼亚语
} else if (language.endsWith("sv")) {
return "sv";//sv-瑞典语
} else if (language.endsWith("te")) {
return "te";// te-泰国语
} else if (language.endsWith("tr")) {
return "tr";// tr-土耳其语
} else if (language.endsWith("vi")) {
return "vi";//vi-越南语
}
return "en";
}
public static String getServiceLanguage() {
Locale locale = BaseApplication.getInstanceApp().getResources().getConfiguration().locale;
String language = locale.getLanguage();
if (language.endsWith("zh")) {
return "zh";//中文
} else if (language.endsWith("en")) {
return "en";//英文
} else if (language.endsWith("ja")) {
return "ja";//ja-日语
}
return "en";
}
/**
* 如果本机语言是中文返回true否则返回flase
*/
public static boolean getLanguageisChina() {
return TextUtils.equals("zh", getLanguage());
}
/**
* 如果本机语言是中文返回true否则返回flase
*/
public static boolean getLanguageIsJapan() {
return TextUtils.equals("ja", getLanguage());
}
public static boolean getLanguageIsGermany() {//de 德国
return TextUtils.equals("de", getLanguage());
}
public static boolean getLanguageIsSpain() {//es 西班牙
return TextUtils.equals("es", getLanguage());
}
public static boolean getLanguageIsFrance() {//es 法国
return TextUtils.equals("fr", getLanguage());
}
public static boolean getLanguageIsItaly() {//it 意大利
return TextUtils.equals("it", getLanguage());
}
public static boolean getLanguageIsKorea() {//kr 韩国
return TextUtils.equals("ko", getLanguage());
}
public static boolean getLanguageIsNetherlands() {//nl 荷兰
return TextUtils.equals("nl", getLanguage());
}
/**
* 通过国家名称返回国家码
*/
public static String returnCountryCode(String country) {
if (!country.isEmpty()) {
if (country.equals("中国")) {
return "CN";
} else if (country.equals("美国")) {
return "US";
} else if (country.equals("加拿大")) {
return "US";
} else if (country.equals("澳大利亚")) {
return "US";
} else if (country.equals("日本")) {
return "DE";
} else {
return "";
}
}
return "";
}
public static boolean isChina() {
Locale locale = BaseApplication.getInstanceApp().getResources().getConfiguration().locale;
String language = locale.getLanguage();
String country = locale.getCountry();
if (language.endsWith("zh") && !TextUtils.isEmpty(country)) {
if (country.equals("CN")) {
return true;
}
}
return false;
}
public static Context attachBaseContext(Context context, String language) {
if (!TextUtils.isEmpty(language) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context);
} else {
changeAppLanguage(context);
return context;
}
}
@SuppressWarnings("deprecation")
public static void changeAppLanguage(Context context) {
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
// app locale
Locale locale = getSystemLocale();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
configuration.setLocale(locale);
} else {
configuration.locale = locale;
}
// updateConfiguration
DisplayMetrics dm = resources.getDisplayMetrics();
resources.updateConfiguration(configuration, dm);
}
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context) {
Resources resources = context.getResources();
Locale locale = getSystemLocale();
Configuration configuration = resources.getConfiguration();
configuration.setLocale(locale);
configuration.setLocales(new LocaleList(locale));
return context.createConfigurationContext(configuration);
}
private static final String LAST_LANGUAGE = "lastLanguage";
/**
* 当改变系统语言时,重启App
*
* @param activity
* @param homeActivityCls 主activity
* @return
*/
public static boolean isLanguageChanged(Context activity/*, Class<?> homeActivityCls*/) {
Locale locale = activity.getResources().getConfiguration().getLocales().get(0);
if (locale == null) {
return false;
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity);
String lastLocalStr = sp.getString(LAST_LANGUAGE, "");
String curLocaleStr = getLocaleString(locale);
// Log.d("local_lan"," lastLocalStr="+lastLocalStr+"。。。 curLocaleStr="+curLocaleStr);
if (TextUtils.isEmpty(lastLocalStr)) {
sp.edit().putString(LAST_LANGUAGE, curLocaleStr).commit();
return false;
} else {
if (lastLocalStr.equals(curLocaleStr)) {
return false;
} else {
sp.edit().putString(LAST_LANGUAGE, curLocaleStr).commit();
restartApp(activity/*, homeActivityCls*/);
return true;
}
}
}
private static String getLocaleString(Locale locale) {
if (locale == null) {
return "";
} else {
return locale.getCountry() + locale.getLanguage();
}
}
public static void restartApp(Context activity/*, Class<?> homeClass*/) {
final Intent intent = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
activity.startActivity(intent);
// 杀掉进程
try {
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
} catch (Exception e) {
LogUtils.d("restartApp",e.toString());
}
}
/**
* 获取系统Local
*
* @return
*/
public static Locale getSystemLocale() {
return Resources.getSystem().getConfiguration().locale;
}
/**
* 获取国家语言(目前国际化 九国语言)
*/
public static String getCountryLanguge() {
String languge = "en";
if (LanguageUtils.isChina()) {
languge = "zh";
} else if (LanguageUtils.getLanguageIsJapan()) {
languge = "ja";
} else if (LanguageUtils.getLanguageIsGermany()) {
languge = "de";
} else if (LanguageUtils.getLanguageIsSpain()) {
languge = "es";
} else if (LanguageUtils.getLanguageIsFrance()) {
languge = "fr";
} else if (LanguageUtils.getLanguageIsItaly()) {
languge = "it";
} else if (LanguageUtils.getLanguageIsKorea()) {
languge = "kr";
} else if (LanguageUtils.getLanguageIsNetherlands()) {
languge = "nl";
}
return languge;
}
/**
* 获取国家码
*/
public static String getCountryCode() {
String countryCode = "GB";
if (LanguageUtils.isChina()) {
countryCode = "CN";
} else if (LanguageUtils.getLanguageIsJapan()) {
countryCode = "JP";
} else if (LanguageUtils.getLanguageIsGermany()) {
countryCode = "DE";
} else if (LanguageUtils.getLanguageIsSpain()) {
countryCode = "ES";
} else if (LanguageUtils.getLanguageIsFrance()) {
countryCode = "FR";
} else if (LanguageUtils.getLanguageIsItaly()) {
countryCode = "IT";
} else if (LanguageUtils.getLanguageIsKorea()) {
countryCode = "KR";
} else if (LanguageUtils.getLanguageIsNetherlands()) {
countryCode = "NL";
}
return countryCode;
}
}
5.App切换语言立即重启:
使用时在Application的onConfigurationChanged方法调用即可,不用重启app也会立即刷新App的语言.
less
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
LanguageUtils.attachBaseContext(this, LanguageUtils.getLanguage());
}
6.webView完整测试代码如下:
scss
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.webkit.CookieSyncManager;
import android.webkit.GeolocationPermissions;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.powervision.UIKit.dao.GreenDaoManager;
import com.powervision.UIKit.dao.bean.UserData;
import com.powervision.UIKit.mvp.activity.AbsMvpActivity;
import com.powervision.UIKit.router.RouterUtil;
import com.powervision.UIKit.utils.CommonUtils;
import com.powervision.UIKit.utils.LanguageUtils;
import com.powervision.UIKit.utils.NavigationBarUtil;
import com.powervision.UIKit.utils.NetUtils;
import com.powervision.UIKit.utils.ToastUtils;
import com.powervision.UIKit.widget.TipDialog;
import com.powervision.common_base.R;
import com.powervision.pvcamera.module_user.presenter.WebPresenter;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* 网页
*/
@Route(path = RouterUtil.Web.WEB_PATH)
public class WebActivity extends AbsMvpActivity<WebPresenter> implements View.OnClickListener {
private ImageView mBackBt;
private WebView mWebView;
private String url = "";
private String title = "";
private ValueCallback<Uri> mUploadMessage; // 设置上传标识符(下同)
private ValueCallback<Uri[]> mUploadMessageAboveL;
private TextView mTitleTv;
// 上传图片类型
private final static String UPLOAD_IMG_TYPE = "image/jpeg";
public static final String PARAM_URL = "param_url";
public static final String PARAM_NEED_BACK = "param_need_back";
public static final String PARAM_TITLE = "param_title";
private boolean isRefresh = false;
@NonNull
@Override
protected WebPresenter createPresenter(Context context) {
return new WebPresenter(context);
}
@SuppressLint("ObsoleteSdkInt")
@Override
protected int getLayoutResId() {
getWindow().setFormat(PixelFormat.TRANSLUCENT);
try {
if (Build.VERSION.SDK_INT >= 11) {
getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
}
NavigationBarUtil.hideNavigationBar(getWindow());
} catch (Exception e) {
e.printStackTrace();
}
return R.layout.layout_webview;
}
public static void jumpWebViewActivity(Activity activity, String url) {
Intent intent = new Intent(activity, WebActivity.class);
Bundle bundle = new Bundle();
bundle.putString(PARAM_URL, url);
intent.putExtras(bundle);
activity.startActivity(intent);
}
public static Bundle getWebBundle(String url, boolean needBack, String title) {
Bundle bundle = new Bundle();
bundle.putString(PARAM_URL, url);
bundle.putBoolean(PARAM_NEED_BACK, needBack);
bundle.putString(PARAM_TITLE, title);
return bundle;
}
@Override
protected void initView(Bundle savedInstanceState) {
showLoadingDialog(false);
mBackBt = findViewById(R.id.webview_back_iv);
mWebView = findViewById(R.id.webview);
mTitleTv = findViewById(R.id.webview_tilte);
isRefresh = true;
}
@Override
protected void initData() {
if (getIntent() != null) {
url = getIntent().getStringExtra(PARAM_URL);
title = getIntent().getStringExtra(PARAM_TITLE);
boolean booleanExtra = getIntent().getBooleanExtra(PARAM_NEED_BACK, false);
if (booleanExtra) {
mBackBt.setVisibility(View.VISIBLE);
} else {
mBackBt.setVisibility(View.GONE);
}
}
if (TextUtils.isEmpty(url)) {
return;
}
if (!TextUtils.isEmpty(title) && mTitleTv != null) {
mTitleTv.setText(title);
mTitleTv.setVisibility(View.VISIBLE);
}
Log.w("lzq", "initdata load url:" + url);
if (!TextUtils.isEmpty(url)) {
mWebView.loadUrl(url);
initWebView(mWebView);
}
}
@Override
protected void initActions() {
mBackBt.setOnClickListener(this);
}
/**
* 初始化WebView
*/
@SuppressLint("SetJavaScriptEnabled")
private void initWebView(WebView view) {
Log.w("lzq", "initWebView load url");
view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
WebSettings settings = view.getSettings();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
}
settings.setAllowFileAccess(true);
settings.setJavaScriptEnabled(true); // 允许使用JavaScript
settings.setSupportMultipleWindows(true); // 支持多窗口
// 缩放至屏幕的大小
settings.setLoadWithOverviewMode(true);
// 保存表单数据
settings.setSaveFormData(true);
// 是否应该支持使用其屏幕缩放控件和手势缩放
settings.setSupportZoom(true);
// 是否支持手势缩放控制
settings.setBuiltInZoomControls(true);
settings.setUseWideViewPort(true);
settings.setSupportMultipleWindows(true);
settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
// 页面加载好以后,再放开图片
settings.setBlockNetworkImage(false);
// 启动应用缓存
settings.setAppCacheEnabled(true);
settings.setAppCacheMaxSize(Long.MAX_VALUE);
// 使用localStorage则必须打开
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled(true);
settings.setGeolocationEnabled(true);
if (NetUtils.isConnected()) {
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
} else {
settings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
}
// WebView启用JavaScript执行。默认的是false。
settings.setJavaScriptEnabled(true); // 设置支持javascript脚本
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setAppCachePath(this.getDir("appcache", 0).getPath());
settings.setDatabasePath(this.getDir("databases", 0).getPath());
settings.setGeolocationDatabasePath(this.getDir("geolocation", 0).getPath());
settings.setPluginState(WebSettings.PluginState.ON_DEMAND);
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().sync();
view.setWebViewClient(new MWebViewClient());
view.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
FileChooserParams fileChooserParams) {
mUploadMessageAboveL = filePathCallback;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//Android11通过SAF选择图片
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, FILE_CHOOSER_RESULT_CODE);
} else {
openImageChooserActivity();
}
return true;
}
@Override
public View getVideoLoadingProgressView() {
Log.w("lzqWeb", "getVideoLoadingProgressView");
FrameLayout frameLayout = new FrameLayout(WebActivity.this);
frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
return frameLayout;
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
}
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
Log.w("Web", "onShowCustomView");
showCustomView(view, callback);
}
@Override
public void onHideCustomView() {
Log.w("Web", "onHideCustomView");
hideCustomView();
}
@Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
super.onGeolocationPermissionsShowPrompt(origin, callback);
callback.invoke(origin, true, false);
}
});
}
private View customView;
private FrameLayout fullscreenContainer;
private WebChromeClient.CustomViewCallback customViewCallback;
/**
* 视频全屏参数
*/
protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
/**
* 视频播放全屏
**/
private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
// if a view already exists then immediately terminate the new one
if (customView != null) {
callback.onCustomViewHidden();
return;
}
FrameLayout decor = (FrameLayout) getWindow().getDecorView();
fullscreenContainer = new FullscreenHolder(this);
fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
customView = view;
setStatusBarVisibility(false);
customViewCallback = callback;
}
/**
* 隐藏视频全屏
*/
private void hideCustomView() {
if (customView == null) {
return;
}
setStatusBarVisibility(true);
FrameLayout decor = (FrameLayout) getWindow().getDecorView();
Log.w("lzqWeb", "height:" + decor.getHeight());
Log.w("lzqWeb", "width:" + decor.getWidth());
decor.removeView(fullscreenContainer);
fullscreenContainer = null;
customView = null;
customViewCallback.onCustomViewHidden();
mWebView.setVisibility(View.VISIBLE);
}
/**
* 全屏容器界面
*/
static class FullscreenHolder extends FrameLayout {
public FullscreenHolder(Context ctx) {
super(ctx);
setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
}
@Override
public boolean onTouchEvent(MotionEvent evt) {
return true;
}
}
private void setStatusBarVisibility(boolean visible) {
int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
// 回退键 事件处理 优先级:视频播放全屏-网页回退-关闭页面
if (customView != null) {
hideCustomView();
} else if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
finish();
}
return true;
default:
return super.onKeyUp(keyCode, event);
}
}
private class MWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Log.d(Tag, ".拦截.....shouldOverrideUrlLoading()...url=" + url);
if (url.startsWith("http:") || url.startsWith("https:")) {
return false;
}
if (!TextUtils.isEmpty(url) && url.contains("showh5")) {//检测show5
onBackPressed();
return true;
}
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
dismissLoadingDialog();
mWebView.setVisibility(View.VISIBLE);
if (!TextUtils.isEmpty(url) && url.contains("listAftersales")) {
UserData userData = GreenDaoManager.getInstance().getUserData();
if (userData != null) {
mWebView.loadUrl("javascript:getUserIdAndLan(" + "'" + userData.getUserId() + "'"
+ " , " + "'" + LanguageUtils.getServiceLanguage() + "'" + ")");
if (isRefresh) {
mWebView.reload();
isRefresh = false;
}
}
}
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
new TipDialog(WebActivity.this, getString(R.string.Edit_391), getString(R.string.Edit_409),
handler::cancel, handler::proceed).show(true);
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.webview_back_iv) {
if (mWebView != null && mWebView.canGoBack()) {
mWebView.goBack();
} else {
this.onBackPressed();
}
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
LanguageUtils.attachBaseContext(this, LanguageUtils.getLanguage());
if (mWebView != null) {
mWebView.loadUrl(url);
mWebView.reload();
}
}
@Override
protected void onDestroy() {
dismissLoadingDialog();
if (mWebView != null) {
mWebView.clearFormData();
mWebView.clearHistory();
mWebView.clearCache(true);
mWebView.getSettings().setDatabasePath(null);
mWebView.getSettings().setAppCachePath(null);
mWebView.stopLoading();
mWebView.removeAllViews();
ViewParent parent = mWebView.getParent();
if (parent != null) {
((ViewGroup) parent).removeView(mWebView);
}
mWebView.clearView();
mWebView.destroy();
mWebView = null;
}
super.onDestroy();
}
}
7.总结:
以上就是今天的内容在国际化多语言切换时webview不及时刷新问题,尝试了三种方法才最终解决。这里就不放效果截图了,有需要的同学可以尝试一下,小伙伴们如果有更好地方法,可以给我留言,让我也学习一下,希望本文章对各位同学有所帮助,谢谢大家,一个来自游离在各小厂的菜鸟程序员所记,谢谢~~