问题
Situation
I have a fairly simple app with 2 "layouts" using SharedPreferences.
- Main.xml
- Settings.xml
Main has a textView that uses getString from SharedPreferences. Also a button to open Settings.
Settings has a spinner and a button to save to SharedPreferences.
The textView gets updated when the App loads as I am calling setText() inside onCreate(Bundle savedInstanceState)
Problem
When I open Settings and update the SharedPreferences, I use the Back button to get back to Main.
Since I am calling setText() inside onCreate() the textView does not update again until I exit the app and open the app again to main.
What method do I need to use to update the textView after coming back from Settings?
My request is similar to the viewWillAppear() for iOS.
回答1:
onCreate() is only called once when the activity first starts. If you want to update text whenever the activity becomes active you can use onResume() instead. More information on the Activity lifecycle can be found here.
回答2:
You can also create an OnSharedPreferenceChangeListener. Register it in your Activity.onCreate()
with PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener()
. Also unregister it in Activity.onDestroy()
with PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener()
.
回答3:
You could also start your Settings activity with startActivityForResult and then implement an onActivityResult method in your Main activity: StartingActivities
回答4:
the best solution I found is to override onVisibilityChanged
@Override
protected void onVisibilityChanged(View changedView, int visibility){
super.onVisibilityChanged(changedView, visibility);
if(visibility==VISIBLE ){
Log.v("View will appear", "");
}
else{
Log.v("View will disappear", "");
}
}
来源:https://stackoverflow.com/questions/8420837/android-sdk-equivlent-for-viewwillappear-ios