0
僅當單擊按鈕以更改應用程序語言配置時才調用受保護的方法。由於我是Android和java的新手,我無法找到出路。提前致謝。單擊按鈕後加載受保護的方法
@Overide
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_language);
btnAss = (RadioButton) findViewById(R.id.radioButtonAss);
btnEng = (RadioButton) findViewById(R.id.radioButtonEng);
btnSubmit = (Button) findViewById(R.id.btnSelectLanguage);
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (btnAss.isChecked()) {
//here it should call the protected method attachBaseContext
// attachBaseContext(getApplicationContext());
Intent intent = new Intent(getApplicationContext(), WelcomeActivity.class);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(getApplicationContext(), WelcomeActivity.class);
startActivity(intent);
finish();
}
}
});
}
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(MyContextWrapper.wrap(newBase,"as"));
}
的ContextWrapper如下
public class MyContextWrapper extends ContextThemeWrapper {
public MyContextWrapper(Context base) {
super(base,R.style.AppTheme);
}
@SuppressWarnings("deprecation")
public static ContextWrapper wrap(Context context, String language) {
Configuration config = context.getResources().getConfiguration();
Locale sysLocale = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
sysLocale = getSystemLocale(config);
} else {
sysLocale = getSystemLocaleLegacy(config);
}
if (!language.equals("") && !sysLocale.getLanguage().equals(language)) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
setSystemLocale(config, locale);
} else {
setSystemLocaleLegacy(config, locale);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
context = context.createConfigurationContext(config);
} else {
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
}
}
return new MyContextWrapper(context);
}
@SuppressWarnings("deprecation")
public static Locale getSystemLocaleLegacy(Configuration config){
return config.locale;
}
@TargetApi(Build.VERSION_CODES.N)
public static Locale getSystemLocale(Configuration config){
return config.getLocales().get(0);
}
@SuppressWarnings("deprecation")
public static void setSystemLocaleLegacy(Configuration config, Locale locale){
config.locale = locale;
}
@TargetApi(Build.VERSION_CODES.N)
public static void setSystemLocale(Configuration config, Locale locale){
config.setLocale(locale);
}
}
是的,但默認情況下,當活動加載attachBaseContext方法時會被調用,但必須在點擊按鈕後才能調用。 – dhruv