简体   繁体   中英

Android - do something in activity when preferences change

I have two classes, CustomerPreferences which extends PreferenceActivity implements OnSharedPreferenceChangeListener and CustomerActivity which extends Activity . In CustomerActivity , I calculate some values. In CustomerPreferences there's a particular ListPreference I want to monitor. When the user enters CustomerPreferences --which is done via a menu option on CustomerActivity --and changes that ListPreference , then hits the back button and returns to CustomerActivity , I want to recalculate my values based on the new preference setting. If the user goes into CustomerPreferences but doesn't change the value of the ListPreference , I don't want to recalculate anything upon return to CustomerActivity .

How can I do this?

I figure I'll need to do something in CustomerPreferences.onSharedPreferenceChanged as well as maybe CustomerPreferences.onBackPressed , then probably handle something in CustomerActivity .

You can handle the change in CustomerActivity's onResume() method. So after the user presses back, in onResume(), go through your preferences and recalculate your values and change your GUI representation based on the calculated values.

Sure, sometimes this will be unnecessary as the user may not have changed anything. As long as your calculations aren't too heavy this should not be cause for concern.

Another thing you can do is set a boolean in shared preferences such as preferencesChanged which will get set to true in CustomerPreferences.onSharedPreferenceChanged. Then check preferencesChanged in onResume(). If true do your recalculations. Otherwise do nothing.

Another option is to start the preferences activity for a result with startActivityForResult(). Then do the recalculations in onActivityResult() in CustomerActivity. The result value would be set in CustomerPreferences.onSharedPreferenceChanged

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM