Reload Preferences in PreferenceActivity on Resume

 ̄綄美尐妖づ 提交于 2019-11-30 03:41:16

问题


In my app, some settings can possibly be changed while the PreferenceActivity is not open, and an issue I'm running into is that addPreferencesFromResource is called in onCreate, so say, I open the PreferenceActivity, then go to another screen from there, then do something that changes the settings, then hit the back key to go back to the PreferenceActivity, then certain settings have not changed on the layout.

So, how could I re-load all the Preferences every time onResume (or onStart()) is called without duplicating the layout?


回答1:


edit: This solution will work for API 11 + only.

Im not sure I fully understand your problem, but you could add a call to recreate() into the onResume of the activity which from my understanding has the activity go through the entire lifecycle again.

In order to make sure that you only do this when there is in fact dirty data, I would set a flag in the SharedPreferences that lets your activity know in the onResume() that it needs to be recreated.

    public void onResume(){
            super.onResume();
            SharedPreferences pref = getApplicationContext().getSharedPreferences(Constants.PREFS_NAME, Context.MODE_PRIVATE);
            if(pref.getBoolean("isDirtyPrefs", true))
                recreate();
        }



回答2:


I had a similar problem. Failing to find a simple way to make my PreferenceActivity refresh itself, my solution was to add this to my PreferenceActivity:

/**
 * Called when activity leaves the foreground
 */
protected void onStop() {
    super.onStop();
    finish();
}

This will cause the Prefs screen to reload from SharedPreferences next time it is started. Needless to say, this approach won't work if you want to be able to go back to your preferences screen by using the back button.



来源:https://stackoverflow.com/questions/7466189/reload-preferences-in-preferenceactivity-on-resume

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!