Separate preferences for each view in an Android app

依然范特西╮ 提交于 2020-01-02 05:32:05

问题


I have multiple views that come and go as the application runs. I want each view to have its own personal preferences that are stored as the ID tag of the view. Above these is the "General Preferences" that the sub prefs reference to get their default values when a view it is created.

Right now I have it set up that the General Preferences are the default SharedPreferences. But I have no Idea how to create the new preferences and set up an activity UI so the user can change them. Is it pretty much the same as setting up the SharedPreferences?


回答1:


this may not be exactly what you're asking for, but here's what I do:

in my main activity, when I call the preferences activity, I pass it the name of the custom preference file as extra data in the intent:

static final String EXTRA_PREFERENCES_NAME = "android.intent.extra.PREFERENCES_NAME";
...
Intent intent = new Intent(this, Preferences.class);
intent.putExtra(EXTRA_PREFERENCES_NAME, preferencesName);
startActivity(intent);

then, in my preferences activity, I get the custom preferences name and set it like this:

public class Preferences extends PreferenceActivity {
    private String preferencesName = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // get the custom preferences name from the extra data in the intent
    preferencesName = getIntent().getExtras().getString(MainActivity.EXTRA_PREFERENCES_NAME);
    // set the preferences file name
    getPreferenceManager().setSharedPreferencesName(preferencesName);
    // get the default preferences from XML
    addPreferencesFromResource(R.xml.preferences);
}

lastly, in my main activity, I get specific preferences like this:

SharedPreferences preferences = getSharedPreferences(preferencesName, MODE_PRIVATE);
String somePreference = preferences.getString("somePreference", defaultValue);



回答2:


Somehow I am not worthy to comment but to write an answer, so here we go: I'd really like to know how to use sharedPreferences with PreferencesActivity instead of DefaultSharedPreferences.

One way I can think of to accomplish this is letting the preferenceActivity save the values to defaultSharedPreferences and then read these values out and save them into a sharedPreferences associated with a name that would match the kind of values saved.

But this seems very wrong. So how do you guys do this? Or do you save all your values from any PreferencesActivties into defaultSharedPreferences?




回答3:


You can use PreferenceManager to achieve the objective.



来源:https://stackoverflow.com/questions/4717807/separate-preferences-for-each-view-in-an-android-app

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