我有两种语言的应用程序(英语和波斯语)。我已经为波斯语言使用了自定义字体。当语言应用程序更改为英语时,数字文本也将保留为波斯格式。我已经使用calligraphy3
库来设置自定义字体。配置字体和设置语言是我的Application类。
public class MyApplication extends MultiDexApplication {
private Locale locale = null;
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Configuration config=new Configuration(newConfig);
if (locale != null) {
config.locale = locale;
Locale.setDefault(locale);
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}
}
@Override
public void onCreate() {
super.onCreate();
/* initialize calligraphy3 library */
ViewPump.init(ViewPump.builder()
.addInterceptor(new CalligraphyInterceptor(
new CalligraphyConfig.Builder()
.setDefaultFontPath("fonts/isans.ttf")
.setFontAttrId(R.attr.fontPath)
.build()))
.build());
/* for localization app */
Configuration conf = getBaseContext().getResources().getConfiguration();
Configuration config = new Configuration(conf);
Log.e(TAG, "pref lag: " + prefHelper.getMyLanguage());
String lang = prefHelper.getMyLanguage();
if (!"".equals(lang) && !config.locale.getLanguage().equals(lang)) {
locale = new Locale(lang);
Locale.setDefault(locale);
config.locale = locale;
config.setLayoutDirection(locale);
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}
/* method I use for changing language of app */
public static void resetLang(int item, Context context) {
String lang = "";
switch (item) {
case PERSIAN:
lang = PERSIAN_LANGUAGE;
break;
case ENGLISH:
lang = ENGLISH_LANGUAGE;
break;
}
Log.e(TAG, "lang: " + lang);
MyApplication.prefHelper.putLanguage(lang);
//setNewLocale(lang, true);
Locale myLocale = new Locale(lang);
Resources res = context.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
conf.setLayoutDirection(myLocale);
res.updateConfiguration(conf, dm);
Intent i = new Intent(context, MainActivity.class);
context.startActivity(i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
System.exit(0);
}
}
在基本活动中,我重写了此方法来应用字体:
public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase));
}
}