在不访问所有视图或按钮ID的情况下更改Android语言



我有下面的代码可以更改活动的语言,但问题是我必须知道我的视图和按钮的所有ID才能更改语言。我想要的是根据所选的字符串自动加载新的字符串集,而不是像下面的那样逐个加载

public class MainActivity extends AppCompatActivity {
TextView messageView;
Resources resources;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//builder.setMessage(getResources().getString(R.string.fire));
builder.setTitle(getResources().getString(R.string.language));
builder.setCancelable(false);
builder.setItems(R.array.languages,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Context context=getApplicationContext();
String[] languages_array = context.getResources().getStringArray(R.array.languages);
Log.d("alert", "the index is: " + languages_array[which]);
String msg="";
if (languages_array[which].equals("Chichewa"))msg="ny";
else msg="en";
messageView = (TextView) findViewById(R.id.textView);
context = LocaleHelper.setLocale(MainActivity.this, msg);
resources = context.getResources();
messageView.setText(resources.getString(R.string.language));
}});
AlertDialog alert = builder.create();
alert.show();
}
}

我已经尝试了以下代码,但它根本不起作用

Configuration overrideConfiguration = getBaseContext().getResources().getConfiguration();
overrideConfiguration.setLocale(new Locale(msg));
Context context2  = createConfigurationContext(overrideConfiguration);
Resources resources = context2.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
resources.updateConfiguration(overrideConfiguration,dm);

要在一个fellswoop中更改语言,需要重新启动Activity

Configuration overrideConfiguration = getBaseContext().getResources().getConfiguration();
overrideConfiguration.setLocale(new Locale(msg));
Context context2 = createConfigurationContext(overrideConfiguration);
Resources resources = context2.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
resources.updateConfiguration(overrideConfiguration, dm);
//Here
recreate()

相关内容

最新更新