Android:从 SharedPreferences 更新显示的首选项

发布于 2025-01-05 09:57:20 字数 2391 浏览 0 评论 0原文

我正在编写一个带有preferencesActivity 的android 应用程序,其中在preferencesActivity 实例中所做的选择会影响显示的其他首选项项的值。虽然我能够以编程方式更改基础 SharedPreferences 项的值,但这些更改的值不会反映在显示的列表项中,直到我退出偏好活动并重新加载它。下面是我的设置类和 xml 文件的精简版本,说明了问题。如果用户将 Guitar 设置为带有键乐器列表的首选项的值,我希望带有键 adjustmentChoice 的首选项恢复为标准。

//necessary import declarations go here
public class Settings extends PreferenceActivity implements OnSharedPreferenceChangeListener{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
        app_preferences.registerOnSharedPreferenceChangeListener(this);
    }

    public void  onSharedPreferenceChanged  (SharedPreferences  sharedPreferences, String  key)   {
        Log.d("onSharedPreferencesChanged", "sharedPreferences changed.  key: " + key);
        Editor preferencesMod = sharedPreferences.edit();
        String instrumentChoice = sharedPreferences.getString("instrumentList", "Guitar");
        if(key.equals("instrumentList")) {
            Log.d("Settings", "key is instrumentList.  chooseTuning before if: " +    sharedPreferences.getString("chooseTuning", "no luck"));
            if(instrumentChoice.equals("Guitar")) {
                preferencesMod.putString("chooseTuning", "Standard");
                preferencesMod.commit(); 
                Log.d("Settings", "chooseTuning after if: " +      sharedPreferences.getString("chooseTuning", "ciao"));
            }
        }
    }
}

我可以在 onSharedPreferenceChanged 方法中再次调用 addPreferencesFromResource ,并加载

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
        android:title="Settings">
  <ListPreference android:title="Choose an Instrument" android:key="instrumentList" android:entryValues="@array/instruments" android:entries="@array/instruments"/>
        <ListPreference android:title="Choose Tuning" android:key="chooseTuning" android:entryValues="@array/tuningChoices" android:entries="@array/tuningChoices" android:persistent="true"/>
</PreferenceScreen>

所有首选项项目的副本,显示在旧项目下方,并具有正确的值。如果我能找到某种方法来取消 onCreate 期间调用的初始 addPreferencesFromResource,我想我会被设置。

任何帮助将不胜感激,谢谢

I'm writing an android app with a preferencesActivity in which selections made in my instance of preferencesActivity affect the values of other preferences items displayed. While I'm able to change the values of the underlying SharedPreferences items pogrammatically, those changed values aren't reflected in the displayed list items until I exit my preferencesActivity and reload it. Below is a stripped down version of my settings class and xml file which illustrate the problem. If a user sets Guitar as the value for the preference with the key instrumentList, I'd like the preference with key tuningChoice to revert to Standard.

//necessary import declarations go here
public class Settings extends PreferenceActivity implements OnSharedPreferenceChangeListener{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
        app_preferences.registerOnSharedPreferenceChangeListener(this);
    }

    public void  onSharedPreferenceChanged  (SharedPreferences  sharedPreferences, String  key)   {
        Log.d("onSharedPreferencesChanged", "sharedPreferences changed.  key: " + key);
        Editor preferencesMod = sharedPreferences.edit();
        String instrumentChoice = sharedPreferences.getString("instrumentList", "Guitar");
        if(key.equals("instrumentList")) {
            Log.d("Settings", "key is instrumentList.  chooseTuning before if: " +    sharedPreferences.getString("chooseTuning", "no luck"));
            if(instrumentChoice.equals("Guitar")) {
                preferencesMod.putString("chooseTuning", "Standard");
                preferencesMod.commit(); 
                Log.d("Settings", "chooseTuning after if: " +      sharedPreferences.getString("chooseTuning", "ciao"));
            }
        }
    }
}

xml file preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
        android:title="Settings">
  <ListPreference android:title="Choose an Instrument" android:key="instrumentList" android:entryValues="@array/instruments" android:entries="@array/instruments"/>
        <ListPreference android:title="Choose Tuning" android:key="chooseTuning" android:entryValues="@array/tuningChoices" android:entries="@array/tuningChoices" android:persistent="true"/>
</PreferenceScreen>

I can call addPreferencesFromResource again in my onSharedPreferenceChanged method and that loads a duplicate of all the preferences items, displayed below the old items, with the correct values. If I could figure out some way to cancel out the initial addPreferencesFromResource called during onCreate, I guess I would be set.

Any help would be appreciated, Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦断已成空 2025-01-12 09:57:21

您需要防止 addPReferencesFromResource 运行两次吗?这是加载你的默认值吗?如果是这样,请添加一个名为 DEFAULTS_LOADED 的附加 SharedPreference,并在创建时读取其值,如下所示:(警告 PSUEDO 代码):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);

    boolean loadDefaults = app_preferences.getBoolean(DEFAULTS_LOADED, true);
    if(loadDefaults)
    {  
        addPreferencesFromResource(R.xml.preferences);
        Editor editor = app_preferences.edit();
        editor.putBoolean(DEFAULTS_LOADED, true);
        editor.commit();
    } 
    app_preferences.registerOnSharedPreferenceChangeListener(this);
}

这将防止每次活动启动时将默认值写入共享首选项。我认为这至少是您问题的一部分。

You need to prevent addPReferencesFromResource from running twice? Is this loading your default values? If so, add an additional SharedPreference called DEFAULTS_LOADED and read its value in on create like: (WARNING PSUEDO CODE):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);

    boolean loadDefaults = app_preferences.getBoolean(DEFAULTS_LOADED, true);
    if(loadDefaults)
    {  
        addPreferencesFromResource(R.xml.preferences);
        Editor editor = app_preferences.edit();
        editor.putBoolean(DEFAULTS_LOADED, true);
        editor.commit();
    } 
    app_preferences.registerOnSharedPreferenceChangeListener(this);
}

This will prevent you defaults from being written to the shared preferences every time your activity starts. I assume this is at least a portion of your issue.

与君绝 2025-01-12 09:57:21

如果有人遇到这个问题,这就是解决方案:

ListView list = preferenceActivity.getListView();
list.performItemClick(list, 1, list.getItemIdAtPosition(1));

If anyone comes to this problem, this is the solution:

ListView list = preferenceActivity.getListView();
list.performItemClick(list, 1, list.getItemIdAtPosition(1));
过期以后 2025-01-12 09:57:21

也许我回答这个问题已经太晚了。但是,我希望这可以帮助像我这样的初学者。

PackageInfo packageInfo = null;
try {
    packageInfo = preference.getContext().getPackageManager().getPackageInfo(preference.getContext().getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();   

}
preference.setSummary(packageInfo.versionName);

Maybe I am too late for answering this. But, I hope this might help beginner like me.

PackageInfo packageInfo = null;
try {
    packageInfo = preference.getContext().getPackageManager().getPackageInfo(preference.getContext().getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();   

}
preference.setSummary(packageInfo.versionName);
将军与妓 2025-01-12 09:57:20

我沿着这些思路做了一些事情......希望它有帮助:

    ListPreference list = (ListPreference) getPreferenceManager().findPreference("myList");
    list.setValue(sharedPrefs.getString("myList", "default"));
    list.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            sharedPrefs.put("myList", newValue.toString());
            return true;
        }

    });

I do something along these lines...hopefully it helps:

    ListPreference list = (ListPreference) getPreferenceManager().findPreference("myList");
    list.setValue(sharedPrefs.getString("myList", "default"));
    list.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

        public boolean onPreferenceChange(Preference preference, Object newValue) {
            sharedPrefs.put("myList", newValue.toString());
            return true;
        }

    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文