我能够使用本文中介绍的方法在运行时以编程方式更改本地化。我能够更改应用程序的语言。+ 布局方向 + 工具栏语言。
这是我的代码:
构建.gradle
buildTypes {
debug {
pseudoLocalesEnabled true
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.jakewharton:process-phoenix:2.0.0'
}
public class App extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleManager.setLocale(base));
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
LocaleManager.setLocale(this);
if (Build.VERSION.SDK_INT >= 26) {
ProcessPhoenix.triggerRebirth(this); //An activity must have a category of Default in Manifest!
}
}
}
public class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT>=26) {
LocaleManager.setLocale(this);
}
startActivity(new Intent(this,MainActivity.class));
finish();
}
}
public class LocaleManager {
private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
private static final String DEFAULT_LANGUAGE = "en";
public static Context setLocale(Context c) {
return setNewLocale(c, getLanguage(c));
}
public static Context setNewLocale(Context c, String language) {
persistLanguage(c, language);
return updateResources(c, language);
}
public static String getLanguage(Context c) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(c);
return preferences.getString(SELECTED_LANGUAGE, DEFAULT_LANGUAGE);
}
public static void persistLanguage(Context c, String language) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(c);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SELECTED_LANGUAGE, language);
editor.commit();
}
private static Context updateResources(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Resources res = context.getResources();
Configuration config = new Configuration(res.getConfiguration());
if(Build.VERSION.SDK_INT >= 17) {
config.setLocale(locale);
res.updateConfiguration(config, res.getDisplayMetrics());
}
return context;
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Change English to arabic when user clicked the button.
public void changeLanguage(View view) {
LocaleManager.persistLanguage(this ,"ar");
LocaleManager.setLocale(this);
ProcessPhoenix.triggerRebirth(this); //An activity must have a category of Default in Manifest!
问题: 在我迁移到 androidX 之前,这段代码一直运行良好。现在,它仅适用于装有 Android Oreo+ 的设备。我在迁移到 androidX 之前检查了一个备份版本,它运行良好。我在这里缺少什么吗?