Which settings file does PreferenceFragment read/write?

自古美人都是妖i 提交于 2019-12-03 08:56:27

问题


How can I control which file should be used by a PreferencesFragment for reading and writing settings? I can't find anything about that in the docs. If that can't be controlled via code or XML resources, are there any guarantees, what the file is called, so I can open it explicitly using

Activity.getSharedPreferences(String name, int mode)

Thanks.


回答1:


You have to manipulate the PreferenceManager of the SettingsFragment. This is what it looks like

// Constants
//--------------------------------------------------------------------------
private final static String TAG = SettingsFragment.class.getName();
public final static String SETTINGS_SHARED_PREFERENCES_FILE_NAME = TAG + ".SETTINGS_SHARED_PREFERENCES_FILE_NAME";

// Life-cycle
//--------------------------------------------------------------------------
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate()");

    // Define the settings file to use by this settings fragment
    getPreferenceManager().setSharedPreferencesName(SETTINGS_SHARED_PREFERENCES_FILE_NAME);

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.preferences);
}

Then you can access this settings file outside of the fragment like this:

SharedPreferences preferences = getActivity().getSharedPreferences(
        SettingsFragment.SETTINGS_SHARED_PREFERENCES_FILE_NAME,
        Context.MODE_PRIVATE);


来源:https://stackoverflow.com/questions/17880437/which-settings-file-does-preferencefragment-read-write

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