开发者

Android: adding and removing a SharedPreference

I'm having a bit of an issue comparing key strings in an OnSharedPreferenceChanged method and hoped you might be able to take a look at it - basically the problem is that even when i know and can console log the exact string for the comparison, the code in the statement block never fires - i know it's something stupid but i just can't see it

thanks in advance

obie

here's the code

public class WallpaperSettings extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener
{
    public static final String TAG = "WallpaperSettings";
    private static final String USE_CLOCK_TEXT = "useClockText";

    private Preference _clockTextPosPicker;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getPreferenceManager().setSharedPreferencesName(HexClockWallpaper.SHARED_PREFS_NAME);
        addPreferencesFromResource(R.xml.hexclockwallpaper_settings);
        getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onDestroy()
    {
        getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
        super.onDestroy();
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
            String key)
    {
        // [Log] key: 'useClockText'
        Log.i(TAG, "key: '" + key + "'");
        if (key == USE_CLOCK_TEXT)
        {
            // None of this is ever seen
            Log.i(TAG, "key == " + USE_CLOCK_TEXT);

            Boolean selected = sharedPreferences.getBoolean(key, true);
            Log.i(TAG, "selected changed: " + selected);
            if (selected)
        开发者_开发百科    {
                getPreferenceScreen().removePreference(getClockTextPicker());
            }
            else
            {
                getPreferenceScreen().addPreference(getClockTextPicker());
            }
        }
    }

    public Preference getClockTextPicker()
    {
        if (_clockTextPosPicker == null)
            _clockTextPosPicker = findPreference("clockTextPosPicker");

        return _clockTextPosPicker;
    }
}


To compare two String objects you must use string1.equals(string2). Here's a link you might find useful: Java String Comparison

Good luck!


When comparing strings in Java use the equals method of Object

e.g. if ( string1.equals(string2) ) { ... }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜