要改变所有版本的Android应用程序语言,可以遵循以下步骤:
在应用程序的res
文件夹中创建不同语言的资源文件夹。例如,如果你想要支持英语和西班牙语,可以在res
文件夹下创建values-en
和values-es
文件夹。
在每个资源文件夹中创建一个strings.xml
文件,用于存储对应语言的字符串资源。
在strings.xml
文件中为每个字符串资源提供相应语言的值。例如,在values-en
文件夹下的strings.xml
中,可以将一个字符串资源app_name
的值设置为My App
,而在values-es
文件夹下的strings.xml
中,可以将其值设置为Mi Aplicación
。
在应用程序的AndroidManifest.xml
文件中,为application
标签添加android:configChanges="locale"
属性,以便应用程序可以响应语言更改。
创建一个BaseActivity
类,并在其中重写attachBaseContext
方法。在该方法中,使用LocaleHelper
类从SharedPreferences
中获取当前选择的语言,并将其应用于应用程序的上下文。
public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(LocaleHelper.onAttach(newBase));
}
}
LocaleHelper
类,用于处理语言更改和应用程序的上下文。public class LocaleHelper {
private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
public static Context onAttach(Context context) {
String language = getPersistedData(context, Locale.getDefault().getLanguage());
return setLocale(context, language);
}
public static Context setLocale(Context context, String language) {
persist(context, language);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return updateResources(context, language);
}
return updateResourcesLegacy(context, language);
}
private static String getPersistedData(Context context, String defaultLanguage) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
}
private static void persist(Context context, String language) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SELECTED_LANGUAGE, language);
editor.apply();
}
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
Locale locale = new Locale(language);
Configuration configuration = context.getResources().getConfiguration();
configuration.setLocale(locale);
configuration.setLayoutDirection(locale);
return context.createConfigurationContext(configuration);
}
@SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, String language) {
Locale locale = new Locale(language);
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.locale = locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
configuration.setLayoutDirection(locale);
}
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
return context;
}
}
BaseActivity
类,以便它们可以响应语言更改。public class MainActivity extends BaseActivity {
// Activity code here
}
这样,当用户更改应用程序的语言设置时,应用程序将重新加载,并显示适当的语言资源。