问题
I have a main activity (let's call it A) and a second activity (let's call it B) which's used to change the language of the app. The point is, when I click the button to change the language I also call recreate();
and B changes it language. Until here it's ok. The problem comes when I go back to the main activity (A) and it hasn't updated the language because it hasn't been recreated, so, is there any way to recreate A from B in order to update A?
I use this code to translate the app (eng version example):
public void btnIngles_onClick(View v)
{
Locale locale = new Locale("en");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
this.getApplicationContext().getResources().updateConfiguration(config, null);
recreate();
}
回答1:
1) Activity B
changes some global settings, accessible via SharedPreferences
for example
2) In Activity A
do:
@Override
protected void onResume() {
super.onResume();
if(didLanguageChange)
recreate();
}
Problem solved. Activity A
will call onResume()
since it has switched into a paused state when Activity B
came into the foreground.
回答2:
You need to implement onActivityResult()
in your Activity. This link has more information and should be very helpful to you. In a nutshell:
Inside your Activity A, you'll need to create a variable used as a request code, something like this:
private static final int ACTIVITY_B_REQUEST = 0;
And then, in your button's onClick listener, you'll start the activity using an intent and the startActivityForResult()
function:
Intent myIntent = new Intent(ActivityA.this, ActivityB.class);
startActivityForResult(myIntent, ACTIVITY_B_REQUEST);
This will start Activity B for you. Whenever Activity B finishes, onActivityResult
will be called. You can override it and implement it in whichever way you need, but it may look something like this:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == ACTIVITY_B_REQUEST && resultCode == RESULT_OKAY){
// Handle this by doing what you need to refresh activity A.
} else{
super(requestCode, resultCode, data);
}
}
回答3:
Restart your app:
startActivity(new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent
.FLAG_ACTIVITY_CLEAR_TOP));
来源:https://stackoverflow.com/questions/29106504/how-to-recreate-previous-activity