OnSharedPreferenceChangeListener not registering change in preference

时光总嘲笑我的痴心妄想 提交于 2019-12-04 22:43:13
Femi

Your code looks like it should work: you can try logging out to ensure its doing what it should. Move all the conditional code into the listener.

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
        String key) {
    android.util.Log.v("PREFERENCE CHANGE", "[" + key + "]");
    if ("listPref1".equals(key)) {
        String keys = pref.getString("listPref1", "");
        if (keys == "ON") {
            text.setText("ON");
        } else if (keys == "OFF") {
            text.setText("OFF");
        } else {
            text.setText("Choose One");
        }
    }
}

Your code looks good for registering to hear preference changes, you need to put some code in your onSharedPreferenceChanged method to process the preferences as they are changed. Remember that you will get called back when any preference changes, so you need to do some filtering in the method to make sure it's what you're interested in.

Could be something as simple as:

if(key.equals("listPref1"))
   text.setText("ON"); // Need to make text a class variable

Thank you all for your help, I've sorted most of it out now here is the code

SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this);

    TextView text = (TextView) findViewById(R.id.textView1);

    if (prefs.getString("listPref1", "").equals("OFF")) {
        text.setText("goodbye");
    } else if (prefs.getString("listPref1", "").equals("ON")) {
        text.setText("hello");
    }

    prefs.registerOnSharedPreferenceChangeListener(this);

}

@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    TextView text = (TextView) findViewById(R.id.textView1);

    if (prefs.getString("listPref1", "").equals("OFF")) {
        text.setText("goodbye");
    } else if (prefs.getString("listPref1", "").equals("ON")) {
        text.setText("hello");
    }
}

}

As you can see I have to repeat the if/else statement, if I put it only in the listener nothing gets until a change is made and for if it's only outside the listener it only gets read when the app is first run and changes are not registered.

Isn't there a code to get the listener to notify a change has been made and the code gets re-run?

You don't have any code to actually update your SharedPreferences. The listener will only be triggered when your pref object is edited. Example...

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