1
此刻正在處理Android項目。我試圖實現一個按鈕,可以讓我將語言從英語改爲西班牙語。這是我的代碼:更改本地化語言時的錯誤Android
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//As soon as app is started up create an order object.
order = new Order();
order.setCovers(2);
order.setTable(1);
order.addToOrder(new MenuItem("Item 1", 12.99));
Toast.makeText(getApplicationContext(), "order size: " + order.getItems().size(), Toast.LENGTH_SHORT).show();
//reference to button and add listeners
orderBtn = (Button)findViewById(R.id.orderBtn);
orderBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Create a new intent and start up the sections activity...
i = new Intent(v.getContext(), SectionsActivity.class);
i.putExtra("data", order);
startActivity(i);
}
});
spanishBtn = (Button)findViewById(R.id.spanishBtn);
spanishBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Locale locale = new Locale("es");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}
});
}
該按鈕不會更改語言。它將它作爲英語。但是,如果我使用此代碼在活動頂部運行我的項目,它將以西班牙語加載文本。
Locale locale = new Locale("es");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
我在做什麼錯?任何建議是非常感謝。我希望通過上述代碼實現的是,應用程序以英文啓動,從values-en文件夾中獲取字符串值。然後當我點擊按鈕時,它會從values-es文件夾中加載字符串值。
變化監聽這樣:
spanishBtn = (Button)findViewById(R.id.spanishBtn);
spanishBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Locale locale = new Locale("es");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
MainActivity.this.setContentView(R.layout.activity_main);
}
});
仍然沒有工作...