我的应用程序中有两种语言.values/strings.xml和values-ru/strings.xml当我以编程方式更改语言时,所有字符串都会进行转换,但活动标题不会更改.我在所有活动中使用
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String languageToLoad = prefs.getString("prefLanguage","en");
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
Run Code Online (Sandbox Code Playgroud)
当我选择语言时,重新加载活动或应用程序.
Ant*_*wan 24
我用另一种方式看似愚蠢,但它的工作
在每个活动中尝试从值文件中将操作栏标题设置为您的活动标题
在我的情况下,我正在使用 sherlockactionbar
所以我在oncreate我的productdetails活动中添加了这个
getSupportActionBar().setTitle(getResources().getString(R.string.title_activity_product_details));
Run Code Online (Sandbox Code Playgroud)
添加时setTitle(R.string.activity_title),onCreate()将在运行系统中根据语言环境的变化来更新活动标题以及内容本身。
以下是单击该按钮时将其内容和活动的标题更新为Korea(ko-KR)的简单代码段:
public class MainActivity extends AppCompatActivity {
Button btnReset;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Activity title will be updated after the locale has changed in Runtime
setTitle(R.string.app_name);
btnReset = (Button) findViewById(R.id.button);
btnReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Resources resources = getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
Configuration conf = resources.getConfiguration();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
conf.setLocale(Locale.KOREA);
} else {
conf.locale = Locale.KOREA;
}
resources.updateConfiguration(conf, dm);
// Overwrite the default Locale
Locale.setDefault(Locale.KOREA);
// Clear the back stack then restarts the activity
startActivity(new Intent(MainActivity.this, MainActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| IntentCompat.FLAG_ACTIVITY_CLEAR_TASK));
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
终于得到了解决方案:
resouce Id从中获取活动标题PackageManger,并将AcionBar的标题设置为资源ID,这是因为区域设置已更改,因此android知道要选择哪个活动标题。
try{
ActivityInfo activityInfo = getPackageManager().getActivityInfo(getComponentName(),
PackageManager.GET_META_DATA);
ActionBar actionBar = getActionBar();
if(actionBar != null)
actionBar.setTitle(activityInfo.labelRes);
}catch (PackageManager.NameNotFoundException ex){
Log.e(this.getClass().getSimpleName(),
"Error while getting activity info. " + ex.getMessage(), ex);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4568 次 |
| 最近记录: |